Following is a very simple C program:
char *p = (char*)calloc(5,sizeof(char));
strcpy(p,"Elephant");
printf("String = %s\n", p);
p[6] = 'D';
printf("String = %s\n", p);
which allocates a char array of 5 elements using calloc() and uses strcpy() to copy a string into the array. Following is the output:
String = Elephant
String = ElephaDt
Clearly, I requested for 5 char elements only and hence curious to know why the OS memory mgmt allowed me to store more elements out of the bounds of the dynamically allocated space in p. If I was allocated only a space of 5 characters, how did strcpy() was able to store an even bigger string "Elephant" which is greater than 5 characters in length?
When memory is allocated, this is generally done by a memory manager. These often allocate larger chunks of memory from the OS, and then hand that out to malloc() and friends in smaller parts.
The 5 bytes you allocated are therefore very likely part of a larger chunk of memory. Since you violated the boundaries of your allocation, but not of the larger chunk, the OS does not interfere. It can mean, however, that you corrupted other memory of your own program, by overwriting an allocation nearby. It can even mean you corrupted the data the memory manager uses to keep track of allocated and free memory. But that is not a given. It is simply undefined behaviour.
Undefined behaviour does not mean that you must get a runtime error. It can just as well mean that nothing happens, or that you start WW3, or whatever. It is undefined, but it does not necessarily mean a crash.
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