Why do we need strdup()?

前端 未结 5 1916
花落未央
花落未央 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: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.

提交回复
热议问题