Please tell me the difference between stack and heap with respect to below code
int main()
{
int arr[3];
int *a;
arr [5] = 6; // out of bound but it will not give error.
arr [3000] = 8 ; //SIGSEGV
a = malloc (sizeof (int));
a[4] = 6;
a[4000] = 8; //No error
}
I know that arr is a static array and I am accessing some other process’s address when I do arr[3000] which gives SIGSEGV error. But I don’t understand why a[4000] will not give me any run time error i.e., SIGSEGV signal.
Thanks
It’s not guaranteed that any of those calls actually write to inaccessible memory (which would trigger a segfault). It’s just as likely that the program has permission to write to that memory and doesn’t trigger a segfault, but overwrites some other internal data unrelated to your array. This of course might lead to unexpected effects elsewhere in the program.
Generally this is called undefined behavior. There are no promises made what happens when you write out of the bounds of the array, anything might or might not happen.