Inside a C function, if I declare something like char *s = "Hello"; Where will the memory for the "Hello" string be allocated? Will it be on the stack or the heap?

If it is on the heap, will there be any problem if I return the address of that location (which is 's') from the function??

Thanks.

Recommended Answers

Inside a C function, if I declare something like char *s = "Hello"; Where will the memory for the "Hello" string be allocated? Will it be on the stack or the heap?

Neither.
http://c-faq.com/aryptr/aryptr2.html

Jump to Post

It's stored in the same place as a global variable would be. The "program memory" that is neither "stack" nor "heap". The stuff with static storage duration.

Jump to Post

All 6 Replies

Inside a C function, if I declare something like char *s = "Hello"; Where will the memory for the "Hello" string be allocated? Will it be on the stack or the heap?

Neither.
http://c-faq.com/aryptr/aryptr2.html

Thanks for the answer. I have read the link which you gave and am still confused. I was thinking any memory which my program needs has to be allocated from the stack or the heap. But you said Neither.

Also in that link, the author talks about char *p = "world"; p is a pointer which points to the memory location where "world" is stored.
But he doesn't answer exactly where is this string "world" stored.

It's stored in the same place as a global variable would be. The "program memory" that is neither "stack" nor "heap". The stuff with static storage duration.

A little something about memory

Just out of curiosity, why is it important where?

It was an interview question :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.