Does a string created with 'strcpy' need to be freed?

Kristina Brooks picture Kristina Brooks · Feb 20, 2011 · Viewed 19.6k times · Source

Does a string created with 'strcpy' need to be freed? And how to free it?

Edit: The destination is allocated like this:

char* buffer[LEN];

Answer

paxdiablo picture paxdiablo · Feb 21, 2011

strcpy itself doesn't allocate memory for the destination string so, no, it doesn't have to be freed.

Of course, if something else had allocated memory for it, then, yes, that memory should be freed eventually but that has nothing to do with strcpy.

That previous statement seems to be the case since your definition is an array of character pointers rather than an array of characters:

char* buffer[LEN];

and that will almost certainly be done with:

buffer[n] = malloc (length);

It's a good idea to start thinking in terms of responsibility for malloc'ed memory. By that, I mean passing a malloc'ed memory block may also involve passing the responsibility for freeing it at some point.

You just need to figure out (or decide, if it's your code) whether the responsibility for managing the memory goes along with the memory itself. With strcpy, even if you pass in an already-malloc'ed block for the destination, the responsibility is not being passed so you will still have to free that memory yourself. This allows you to easily pass in a malloc'ed or non-malloc'ed buffer without having to worry about it.

You may be thinking of strdup which is basically making a copy of a string by first allocating the memory for it. The string returned from that needs to be freed, definitely.