C - returns 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);
}

It has no problems compiling and running. However, in my opinion, this should not work, since the memory allocated to the pointer testis on the stack and is destroyed when returning to the main one.

So the question is, how does this work without malloc in the pointerTesting () function?

+5
source share
3 answers

In this case, the string "hello"is stored in global memory *. So it is already highlighted.

Therefore, it still acts when you return from a function.

However, if you did this:

char test[] = "hello";
return test;

, . ( undefined). , , .

* , , .
, - . (. )

+13

test, "hello" (, , char ). test , , .

:

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

, , . , "N-element array of T" " T", .

+5

The trick is that the memory referenced by the test is not on the stack as you expect. See String Literals: Where Do They Go? for some explanation.

+2
source

All Articles