Where is local pointer stored in memory?

Viewed 12700

I am beginner in C. I have one program as below:

int main()
{
    char* func();
    char *c;
    c = func();
    printf("%s", c);
}

char* func()
{
    char *ptr = "OK";
    return ptr;
}

As we all know, ptr is a local variable of func() and is a pointer. The scope is local. But when ptr is returned to the caller, main, it is still valid and when c is printed, it prints "OK".

How is this possible? In which memory segment is ptr stored; stack, or heap?

8 Answers

If you are referring to the location where the string OK is stored, then its stored in the code section of the memory and ptr is stored in the stack.

And the location of OK in code section is still accessible as its address is being returned by func().

Also, the code section is read only. That is the reason why other answers suggested to make your function declaration as:

const char * func ()

That ensures the value pointed to, by returned address to be not modifiable. (pointer to a constant)

Related