How do I use strdup?

c, malloc, strdup

Solution

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

Problem

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?

Original source

Related problems