here's a code that allocates some memory and copies a string into it.
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ char *t ="your_char"; char *s = (char*)malloc(9); memcpy(s,t,9); printf("%s\n",t); printf("%s",s); return 0; } now the output is
your_char your_char☺╚ And that is what I am unable to understand. If I change to memcpy(s,t,10), then there is no garbage value at the end.
I assume it is because of null terminator that also gets copied in second case. But why is there an empty place at all when I have only allocated 9 bytes and they are already occupied by the characters I copied.
"your_char"takes 10 bytes when you count the zero byte, and you need tomalloc10 bytes, and copy all 10 bytes. Otherwise,printfdoesn't know where the string ends.printfhas no way of knowing the number that you passed tomalloc. All it does is look for the zero byte to know where the string ends.