cstrcpy

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


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];

Solution

  • The strcpy function 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, 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];
    

    That would almost certainly be done with something like:

        buffer[n] = malloc (length);
    

    It's a good idea to start thinking in terms of responsibility for dynamically allocated memory. By that, I mean passing such a 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.

    When calling strcpy for example, even if you pass in an dynamically-allocated 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 dynamically allocated block, or some other type of 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.