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