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.
printf
andstrlen
have found a 0 byte after thel
, but you had no right to expect that either. – Steve Jessop