I am getting a segmentation fault while running the following code :-
char *p ="Hello";
*p = 'M';
what I intended was to replace the first character of the string "Hello" with 'M'. But I'm getting segmentation fault. What could be the reason?
I am getting a segmentation fault while running the following code :-
char *p ="Hello";
*p = 'M';
what I intended was to replace the first character of the string "Hello" with 'M'. But I'm getting segmentation fault. What could be the reason?
It's undefined behaviour. For compatibility with old C code, C++ compilers have let you point a non-const pointer at a string literal (e.g. your "Hello"), but you can not write through them portably.
It's best to use:
const char* p = "Hello"; // if you really need a pointer, probably so you
// can move it within the text, point it at other
// text, set it to a NULL sentinel after use...
const char[] hello = "Hello"; // if you're really only interested in the text
Any string literal in C++ and C (for example "Hello" in your code) is of type const char [6] and can implicitly be assigned to any const char * value:
const char * str="Hello";
indicating that it resides in memory marked as read-only by the operating system (you should have gotten a compiler warning). Therefore an exception will be thrown when you try to change that memory location.
The reason why the compiler puts this in read-only memory is because you may be using another identical (or even similar) string literal "Hello" in a different part of your code. By marking the memory location of the string literal as read-only, the compiler only needs to store the string literal once in memory.
Note also, that the C++ standard does not require the compiler putting the string literal into read-only memory, it just says that modifying a string literal is undefined behaviour. In practice however, a string literal is stored in read-only memory on any modern operating system or compiler.
The compiler is putting the string for "Hello" into a read-only memory segment and giving you a pointer to it. The fact that you're allowed to assign the pointer to a char* is done for backwards compatibility. C++ states that it's undefined behaviour.
If you want to alter the string then declare it like this :
char p[]="Hello";