简体   繁体   中英

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?

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)

You're returning the value of test , which is the address of the first character in the string literal "hello" (which, like all string literals, is stored as an array of char in such a way that it's available for the lifetime of the program). If you were trying to return the address of test for later use, then yeah, you'd be running into problems.

Now the following snippet would not work:

char *pointerTesting(void)
{
  char test[] = "hello";
  return test;
}

In this case, you're trying to return the address of the first element in an array object that is local to the function, which will be invalid once the function exits. Remember that in most contexts, an expression of type "N-element array of T" will be replaced with an expression of type "pointer to T" whose value is the address of the first element in the array.

The trick is that the memory referenced by test is not on the stack as you expect. See String literals: Where do they go? for some explanations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM