Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need strdup()?

Tags:

c

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??

like image 697
letsc Avatar asked Nov 02 '10 16:11

letsc


People also ask

Does strdup allocate memory?

The strdup() function allocates sufficient memory for a copy of the string str , does the copy, and returns a pointer to it.

What is the difference between strdup and Strcpy?

The function strcpy() will not allocate the memory space to copy. A pointer to the string to copy and a pointer to place to copy it to should be given. The function strdup() will occupy / grab itself the memory space for copying the string to. This memory space needs to be freed up later when it is of no use anymore.

Is strdup a standard?

strdup( ) function is non standard function which may not available in standard library in C.

Does strdup null terminate?

The strdup() function allocates memory and copies into it the string addressed by s1, including the terminating null character.


2 Answers

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.

like image 110
JaredPar Avatar answered Oct 01 '22 15:10

JaredPar


String literals are stored in the program's data segment. Manipulating their pointers will modify the string literal, which can lead to... strange results at best. Use strdup() to copy them to heap- or stack-allocated space instead.

like image 21
Ignacio Vazquez-Abrams Avatar answered Oct 01 '22 15:10

Ignacio Vazquez-Abrams