Possible Duplicate:
Invalid read/write sometimes creates segmentation fault and sometimes does not
I have the following code:
#include <stdlib.h>
#include <stdio.h>
int main() {
int *ptr = NULL;
ptr = malloc(sizeof(char));
if (ptr) {
*ptr = 10;
printf("sizeof(int): %zu\nsizeof(char): %zu\n", sizeof(int), sizeof(char));
printf("deref of ptr: %d\n", *ptr);
free(ptr);
return EXIT_SUCCESS;
}
else
return EXIT_FAILURE;
}
When I compile and run it, I get following output:
$ gcc test.c
$ ./a.out
sizeof(int): 4
sizeof(char): 1
deref of ptr: 10
The value sizeof(char)
is less than sizeof(int)
. My malloc
call only sets aside enough space for a char
. Yet, my program is able to assign an integer value to ptr
without crashing. Why does this work?
Just because you are writing into unallocated memory does not mean the program will crash. There is no runtime bounds checking like that.
The segfault will occur when you are accessing memory out of the address range allocated through the operating system as detected by the hardware. You may get away with a lot of memory access before then in your heap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With