cstrdup

Why do we need strdup()?


While I was working on an assignment, I came to know that we should not use assignments such as :

 char *s="HELLO WORLD";

Programs using such syntaxes are prone towards crashing.

I tried and used:

 int fun(char *temp)
 {
    // do sum operation on temp
    // print temp.
  }
  fun("HELLO WORLD");

Even the above works(though the output is compiler and standard specific).

Instead we should try strdup() or use const char *

I have tried reading other similar questions on the blog, but could not get the concept that WHY THE ABOVE CODE SHOULDNT WORK.

Is memory allocated?? And what difference does const make??


Solution

  • Lets clarify things a bit. You don't ever specifically need strdup. It is just a function that allocates a copy of a char* on the heap. It can be done many different ways including with stack based buffers. What you need is the result, a mutable copy of a char*.

    The reason the code you've listed is dangerous is that it's passing what is really a constant string in the from of a string literal into a slot which expects a mutable string. This is unfortunately allowed in the C standard but is ihnherently dangerous. Writing to a constant string will produce unexpected results and often crashes. The strdup function fixes the problem because it creates a mutable copy which is placed into a slot expecting a mutable string.