I am calling strdup
and have to allocate space for the variable before calling strdup
.
char *variable;
variable = (char*) malloc(sizeof(char*));
variable = strdup(word);
Am I doing this right? Or is there something wrong here?
The strdup() function allocates sufficient memory for a copy of the string str , does the copy, and returns a pointer to it. The pointer may subsequently be used as an argument to the function free . If insufficient memory is available, NULL is returned and errno is set to ENOMEM .
You don't need to do a malloc() yourself; indeed, it immediately leaks if you do it since you overwrite the only pointer to the space you allocated with the pointer to the space that strdup() allocated. Hence: char *variable = strdup(word); if (variable == 0) …
Use g_strdup() instead of strdup().
The chance of strdup failing is determined by the chance of malloc failing. On modern operating systems with virtual memory, a malloc failure is a very rare thing. The OS may have even killed your entire process before the system gets so low on memory that malloc has to return NULL .
If you're using the POSIX standard strdup()
, it calculates the space needed and allocates it and copies the source string into the newly allocated space. You don't need to do a malloc()
yourself; indeed, it immediately leaks if you do it since you overwrite the only pointer to the space you allocated with the pointer to the space that strdup()
allocated.
Hence:
char *variable = strdup(word);
if (variable == 0) …process out of memory error; do not continue…
…use variable…
free(variable);
If you do need to do the memory allocation, then you need to allocate strlen(word)+1
bytes in variable
and you can then copy word
into that newly allocated space.
char *variable = malloc(strlen(word)+1);
if (variable == 0) …process out of memory error; do not continue…
strcpy(variable, word);
…use variable…
free(variable);
Or calculate the length once and use memmove()
or perhaps memcpy()
:
size_t len = strlen(word) + 1;
char *variable = malloc(len);
if (variable == 0) …process out of memory error; do not continue…
memmove(variable, word, len);
…use variable…
free(variable);
Don't forget to ensure you know where the free()
is for every malloc()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With