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:
int a() { char *a = "a"; printf("%s\n", a); }
int b() { char *b = "a"; *b = 'b'; }
int main() {
b();
a();
return 0;
}
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.
The compiler will put the string "hi" somewhere in memory (it is not imposed where by the standard), and you don't know where, but you have to take into account that it may be placed in a read-only section of memory (though it's the compiler to decide). Then a pointer will be created that points to the beginning to this place in memory.
The memory will not necessarily be freed, as in most cases this string will reside in the data section of memory (in the same place where your compiled instructions will be).
This is not allowed, as the standard does not guarantee write access to such automatically allocated block of memory (see 1.). It may work on some systems/platforms/compilers but it is not guaranteed by the standard.
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