Consider the following code:
char* pointerTesting(void) {
char* test = "hello";
return test;
}
int main() {
char* string = pointerTesting();
printf("string: %s\n", string);
}
This has no problem compiling and running. However, in my understanding, this shouldn't work, as the memory allocated to the test
pointer is on the stack and it's destroyed when returning to main.
So the question is, how does this manages to work without a malloc in the pointerTesting() function?
In this case, the string "hello"
is stored in global memory*. So it's already allocated.
Therefore, it's still valid when you return from the function.
However, if you did this:
char test[] = "hello";
return test;
Then no, it would not work. (undefined behavior) In this case, the string is actually a local array - which is no longer live when the function returns.
*Although this usually is the case, the standard doesn't say that it has to be stored in global memory.
But the important part is that the lifetime of a string literal is the duration of the entire program. (see comments)
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