Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Return a char pointer without malloc

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?

like image 781
Fisher Avatar asked Dec 15 '11 00:12

Fisher


1 Answers

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)

like image 156
Mysticial Avatar answered Sep 23 '22 18:09

Mysticial