Note that there are some explanatory texts on larger screens.

plurals
  1. POHow C strings are allocated in memory?
    primarykey
    data
    text
    <p>Say I have a simple function that returns a C string this way:</p> <pre><code>const char * getString() { const char * ptr = "blah blah"; return ptr; } </code></pre> <p>and I call getString() from main() this way:</p> <blockquote> <pre><code> const char * s = getString(); </code></pre> </blockquote> <p>1) According to gdb, the variable <strong>ptr</strong> is stored on the stack, but <em>the string pointed by ptr</em> is not:</p> <pre><code>(gdb) p &amp;ptr $1 = (const char **) 0x7fffffffe688 (gdb) p ptr $2 = 0x4009fc "blah blah" </code></pre> <p>Does this mean that "blah blah" is not a local variable inside getString()? </p> <p>I guess that if it were a local variable, I would not be able to pass it to my main() function... But if it's not, where is it stored? On the heap? Is that a "kind of" dynamically memory allocation implemented by the OS every time it hits on a string, or what?</p> <p>2) If I use an array instead of a pointer, this way:</p> <pre><code>const char *getString2() { const char a[] = "blah blah blah"; return a; } </code></pre> <p>the compiler warns me that: </p> <p><code>warning: address of local variable ‘a’ returned</code></p> <p>(and of course the program compiles, but it doesn't work).</p> <p>Actually, if I ask gdb, I get</p> <pre><code>(gdb) p &amp;a $2 = (const char (*)[15]) 0x7fffffffe690 </code></pre> <p>But I thought that <strong>const char * ptr</strong> and <strong>const char a[]</strong> were basically the same thing. Looks like they're not.</p> <p>Am I wrong? What is exactely the difference between the two versions?</p> <p>Thank you! </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload