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?
CodePudding user response:
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.
CodePudding user response:
strcpy
does not allocate, thus your second snippet is invalid unless copy
is initialized with some buffer (regardless of it being stack- or heap allocated) or is is a large enough array.
Side note: if you don't know the exact length of the source string, you need to make sure the target buffer size is not exceed (e.g. by using strncpy
or providing a large enough target buffer).
I guess documentation should answer your question in detail.
CodePudding user response:
For starters the pointer copy is not initialized
char *copy;
So this call of strcoy
strcpy(copy, str);
results in undefined behavior.
The pointer copy
must point to a character array where the string pointed to by the pointer str
will be copied.
You need to free what was allocated with malloc, calloc or realloc.
So if the target array pointed to by the pointer copy was dynamically allocated like for example
char *copy = malloc( 10 * sizeof( char ) );
then of course you will need to free the allocated memory when it is not required any more.
This has nothing common with the function strcpy
that just copies a string from one character array to another character array.