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