is it possible to run this code?
Code:#include <stdio.h> int main(void) { char *my_string="Hello"; printf("%s",my_string); *my_string='w'; printf("%c",my_string); return 0; }
is it possible to run this code?
Code:#include <stdio.h> int main(void) { char *my_string="Hello"; printf("%s",my_string); *my_string='w'; printf("%c",my_string); return 0; }
You are not allowed to modify a string literal. Doing so results in undefined behavior.
Generally, no. It may work on some systems, but it is definitely not portable.
Technically, you should say:
If you need to be able to modify the string, then create an actual array to copy the string into:Code:const char *my_string = "Hello";
Empty brackets case the compiler to make the char array exactly the correct size to hold the string, which is the string length + 1 for the null char that marks the end. If you need more space then you need to provide the size:Code:char my_string[] = "Hello";
Code:char my_string[100] = "Hello";
Because the standard mandates that this is the case.
Suggested read: LLVM Project Blog: What Every C Programmer Should Know About Undefined Behavior #1/3
The standard simply does not define the behavior of that operation ("undefined behavior"). Therefore it is completely non-portable. Any particular system may do something sane or insane. It's a crap shoot. Of course, if you're programming just for a particular system that allows it (perhaps an embedded one), and you don't care about portability in general, then it's perfectly okay to do it.
In the case of a string literal, the pointer to the string lives on the stack, and the string itself becomes a part of the executable which on many operating systems may end up in a portion of memory that is read only. In the case of the array, the entire string lives on the stack which in all systems will be writable memory.
thanks for your replies