int main ()
{
char *destination;
char source[10] = "jigarpatel";
destination = (char*) malloc(5);
memcpy(destination, source, 10);
printf("%s and size is %d", destination, strlen(destination));
free(destination);
return 0;
}
Output:
jigarpatel and size is 10
Question:
Here I have allocated just 5 bytes to destination, but the destination length is 10, why is this?
Where are the other bytes stored?
Is it safe in embedded system? Any chances of a crash or a segmentation fault?
How can I detect this type of mistake?
Another Question :
see i am writing one library where user asks for needed memory and library says allocate 10 bytes & then user malloc 10 bytes & pass its pointer to library. now library store some data there…now see if library said to allocate 10 bytes but user has allocated only 5 bytes & give that pointer to library then how can i detect that user hasnt malloc suffecient memory.
This sometimes happens to work but it’s definitely not safe on any system. You are writing past the end of what
mallocis giving you. From the viewpoint of C it’s illegal, but from the viewpoint of the OS it might be ok (that memory might be paged with adequate permissions).Another problem is that if you later call
mallocagain, it might give you some memory including those 5 bytes that you are using without asking. This should provide some interesting debugging sessions.The destination has only
5bytes allocated, but because of the way malloc works on your system, this doesn’t cause an invalid write, since it happens to be inside a valid page.Right after the first 5, for now.
It’s unsafe in any system. Many chances of crashes.
Using valgrind or any memory debugger. A gentle introduction to valgrind can be found here.
¹
For example, on Linux (Glibc), small (~64 bytes)
mallocrequests are served from a small list of preallocated pages called “fastbins”. Each fastbin has a fixed size, and hence using an allocated fastbin up to that size would not trigger a segmentation violation. More details on how this happens can be found here, for a more rigorous treatment of the topic you might refer to the malloc source code.