Why do we need strdup()?

前端 未结 5 1919
花落未央
花落未央 2021-02-20 07:24

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

相关标签:
5条回答
  • 2021-02-20 08:02

    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.

    0 讨论(0)
  • 2021-02-20 08:17

    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.

    0 讨论(0)
  • 2021-02-20 08:27

    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.

    0 讨论(0)
  • 2021-02-20 08:27

    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 讨论(0)
  • 2021-02-20 08:28

    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.

    0 讨论(0)
提交回复
热议问题