Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use strdup?

Tags:

c

malloc

strdup

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?

like image 381
Ivan Zhang Avatar asked Feb 19 '13 00:02

Ivan Zhang


People also ask

How does strdup work in C?

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 .

Do you need to malloc before strdup?

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) …

What can I use instead of strdup?

Use g_strdup() instead of strdup().

Can strdup fail?

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 .


1 Answers

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().

like image 197
Jonathan Leffler Avatar answered Sep 30 '22 16:09

Jonathan Leffler