Search code examples
cstringdynamic-memory-allocationfree

Do you need to free a string from 'strcpy' if you copy a string generated from malloc?


Say I have some code snippet

char *str = malloc(sizeof(char)*10)
// some code to add content to the string in some way

To create a string of 10 chars. If I then copy str with strcpy from the standard string library into a new variable like so

char *copy;
strcpy(copy, str);

I'm aware I then need to free str using free(str), but is that enough? Or does strcpy also dynamically allocate memory for copy if used on a string created from malloc?


Solution

  • Or does strcpy also dynamically allocate memory for copy

    No, strcpy knows nothing about memory, so your code copies a string into an uninitialized pointer pointing at la-la land.

    If you want allocation + copy in the same call, there is non-standard strdup for that (which looks like it will be added to the C standard in the next version of the language).

    Alternatively just do char *copy = malloc(strlen(str)+1); and then strcpy. Keep in mind to always leave room for the null terminator.