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 operation 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??
The strdup() function allocates sufficient memory for a copy of the string str , does the copy, and returns a pointer to it.
The function strcpy() will not allocate the memory space to copy. A pointer to the string to copy and a pointer to place to copy it to should be given. The function strdup() will occupy / grab itself the memory space for copying the string to. This memory space needs to be freed up later when it is of no use anymore.
strdup( ) function is non standard function which may not available in standard library in C.
The strdup() function allocates memory and copies into it the string addressed by s1, including the terminating null character.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With