Question

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];
Was it helpful?

Solution

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.

OTHER TIPS

If you use

char buffer[6];
strcpy(buffer, "hello");

for example, then buffer is freed when the end of its scope is reached.

On the other hand,

char *buffer;
buffer = malloc(sizeof(char) * 6);
strcpy(buffer, "hello");

this way you need to free the memory you allocated.

But it doesn't actually have anything to do with strcpy, only about how you allocate your string.

You provide a pointer to the destination buffer for strcpy, so it depends on how you allocated that buffer as to whether it needs to be freed and how to free it.

For example if you allocated the buffer using malloc, then yes you will need to free it. If you allocated the buffer on the stack then no you will not, it will be released automatically when it goes out of scope.

The strcpy function copies a string into a buffer you need to get some other way (such as malloc); you should free that buffer using whatever mechanism is correct for how you allocated it.

strcpy() doesn't create a string, it only copies a string. Memory allocation is completely separated from that process.

So you have to take care of memory to which the string is copied - if it was allocated dynamically you have to free it at some point. Since you seem to have a stack-allocated buffer you don't have to do anything special - the buffer will be reclaimed when it goes out of scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top