Does memcpy() uses realloc()?

shan picture shan · May 23, 2011 · Viewed 9k times · Source
#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() ?

Answer

iammilind picture iammilind · May 23, 2011

Your code has Undefined Behavior. To answer your question, NO, memcpy doesn't use realloc. sizeof(buf) should be adequate to accomodate strlen(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,

const char* const str = "abcdefghijklmnopqrstuvwxyz";
char* const buff = (char*)malloc(strlen(str) + 1);

Also, don't do *buff++ because you will loose the memory record (what you allocated). After malloc() one should do free(buff) once the memory usage is over, else it's a memory leak.