Search code examples
cmultithreadingstrdup

What happends if you use strdup on an already allocated memory


I'm having some issue with my stack implementation, my push function manipulate the value i send into the function and changes it. I have tried diffrent ways of constructing this but they either don't work or give me corrupted output.

The base idea is the one below here, note: my pop function only walks down one position and doesn't free the memory at the specific position. I can not use strcpy since im working with threads.

Does strdup change the value that it copies, i cant find any information saying that is the case, my understanding is that you are suppose to be able to use the value after it has ben duped.

And how is the correct way to use strdup on a already allocated memory space, i assume that i can't just free it and then use it again.

void stack_push(Stack *s, char *value)
{
   if (s->size == s->capacity) {
       realloc_stack(s);
   }

   if(s->data[s->size] == NULL){
       // The current position does not contain any data.
       s->data[s->size] = strdup(value);

   }
   else{
       free(s->data[s->size]);
       s->data[s->size] = strndup(value, strlen(value) + 1);
   }

   s->size += 1;

}

Edit s->data = char **data


Solution

  • strdup is basically this (no error checking for brevity):

    char *strdup(const char *stringtoduplicate)
    {
      char *newstring = malloc(strlen(stringtoduplicate) + 1);
      strcpy(newstring, stringtoduplicate);
      return newstring;
    }
    

    You use it like this:

    char Foo[] = "Bar";
    char *newBar = strdup(Foo);
    Foo[0] = 'F';
    printf("%s %s\n", Foo, newBar);   // prints: Far Bar
    ...
    free(newBar);     // once you're done with newBar, free it
    

    Now you should be able to answer your own question.