What happends if you use strdup on an already allocated memory

581 views Asked by At

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

2

There are 2 answers

3
Jabberwocky On BEST ANSWER

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.

0
rici On

strdup does not in any way modify its argument. If you look at the prototype for strdup you will see that its parameter is declared const, which means that it is not modified.

strdup can be implemented as:

char* strdup(const char* s) {
    char* n = malloc(strlen(s) + 1);
    if (n) strcpy(n, s);
    return n;
}

There is no magic.

You can use strcpy with threads, by the way. But strdup works fine.