Do I need to free a string created with "strcpy"?

Is it necessary to free a string created with strcpy ? And how to free him?

Edit: The assignment is assigned as follows:

char* buffer[LEN]; 
+7
source share
5 answers

strcpy itself does not allocate memory for the target string, so no, it does not need to be freed.

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

This previous statement seems to be true, since your definition is an array of character pointers, not an array of characters:

 char* buffer[LEN]; 

and this will almost certainly be done with:

 buffer[n] = malloc (length); 

It is a good idea to start thinking in terms of malloc'ed memory responsibility. By this I mean that transferring a malloc memory block may also include transferring responsibility for its release at some point.

You just need to find out (or decide if this is your code) whether it is responsible for managing the memory along with the memory itself. With strcpy , even if you go to an existing malloc'ed block for the recipient, responsibility will not be transferred, so you still have to free this memory yourself. This makes it easy to go to the malloc'ed or non-malloc'ed buffer without worrying about it.

You might be thinking of strdup , which basically creates a copy of the string, first allocating memory for it. The string returned from it must be freed, definitely.

+17
source

If you use

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

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

On the other hand,

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

so you need to free the allocated memory.

But actually it has nothing to do with strcpy, only about how you highlight your line.

+5
source

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

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

+4
source

The strcpy function copies the string to the buffer that you need to get another way (for example, malloc ); you must free this buffer using some mechanism that is correct for how you allocated it.

+2
source

strcpy() does not create a string, it only copies the string. Memory allocation is completely separate from this process.

So, you need to take care of the memory onto which the line is copied - if it was allocated dynamically, you need to free it at some point. Since you seem to have a buffer allocated on the stack, you do not need anything special - the buffer will be fixed when it goes out of scope.

+1
source

All Articles