1- How does this work:
char *ptr = "hi";
Now the compiler will put this string in the memory (I’m guessing the stack), and create a pointer to it? Is this is how it works?
2- Also if it is created locally in a function, when the function returns will the memory occupied by the string be freed?
3- Last but not least, why is this not allowed: ptr[0] = 'H'; ?
1) The string is not (normally) on the stack — it’ll typically be in an initialized data segment that’s read directly from the executable file. The pointer is then initialized to the address of that string.
2) No.
3) Because the standard says it gives undefined behavior. Consider if you had something like this:
Now, when you print out
a, do you expect to get the original value (a) or the updated valued (b)? Compilers can, but don’t necessarily, share such static strings; some also mark that whole area read-only, so attempting to write to it will generate an exception.From the viewpoint of the C standard, the only reasonable answer was to call it undefined behavior.