Originally Posted by
allynm
Hi Jaunty,
I take your point that the system is managing the unused bytes and there is no particular reason to concern oneself with what is done with them. However, if for some reason you write into the buffer more than it was designed (allocated) to hold, there is no way to know you have done so because as long as you don't exceed the total size (used + unused) you will note generate a seg fault.
Regards,
Mark
Unfortunately, the action of overwriting a buffer does not generate a Segmentation Violation. If you happen to overwrite a buffer and trample on some data that your program expects to use at a later time, then this would probably lead to a Segmentation Violation. This is why troubleshooting these types of problems can be tricky.
Here's a crude example that demonstrates how a program continues running:
Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
char* ptr1 = malloc(10);
char* ptr2 = malloc(10);
printf("ptr1 is pointing to: %p\n", ptr1);
printf("ptr2 is pointing to: %p\n", ptr2);
strcpy(ptr2, "Hello World\n");
memset(ptr1, 'J', ptr2-ptr1 + 1); // overwrite buffer with 'J' chars
printf("data at ptr2 is: %s\n", ptr2);
// These are commented out because a SegFault will occur once called.
//free(ptr1);
//free(ptr2);
return 0;
}
Btw, with newer compilers, there is no need to cast the return value of malloc() as dazman19 indicated.
Bookmarks