开发者

Why do we need strdup()?

开发者 https://www.devze.com 2023-01-22 22:28 出处:网络
While I was working on an assignment, I came to know that we should not use assignments such as : char *s=\"HELLO WORLD\";

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 opera开发者_开发知识库tion 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??


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.


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.


String literals may be stored in portions of memory that do not have write privileges. Attempting to write to them will cause undefined behaviour. const means that the compiler ensures that the pointer is not written to, guaranteeing that you do not invoke undefined behaviour in this way.


This is a problem in C. Although string literals are char * you can't modify them, so they are effectively const char*.

If you are using gcc, you can use -Wwrite-strings to check if you are using string literals correctly.


Read my answer on (array & string) Difference between Java and C. It contains the answer to your question in the section about strings.

You need to understand that there's a difference between static and memory allocation and that you don't resort to the same memory spaces.

0

精彩评论

暂无评论...
验证码 换一张
取 消