#inlcude <stdio.h>
#inlcude <stdlib.h>
#inlcude <string.h>
int main() {
char *buff = (char*)malloc(sizeof(char) * 5);
char *str = "abcdefghijklmnopqrstuvwxyz";
memcpy (buff, str, strlen(str));
while(*buff) {
printf("%c" , *buff++);
}
printf("\n");
return 0;
}
this code prints the whole string “abc…xyz”. but “buff” has no enough memory to hold that string. how memcpy() works? does it use realloc() ?
Your code has Undefined Behavior. To answer your question, NO,
memcpydoesn’t userealloc.sizeof(buf)should be adequate to accomodatestrlen(str). Anything less is a crash.The output might be printed as it’s a small program, but in real big code it will cause hard to debug errors. Change your code to,
Also, don’t do
*buff++because you will loose the memory record (what you allocated). Aftermalloc()one should dofree(buff)once the memory usage is over, else it’s a memory leak.