title: What is the lifespan of string literals in C?
body: <p>What is the lifespan of the string literals <code>"zero"</code> and <code>"non-zero"</code> in the following program?</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  const char* tester(int inp)
  {
      const char *retval=NULL;
  
      if (inp==0)
          retval="zero";
      else
          retval="non-zero";
  
      return retval;
  }
  
  int main()
  {
      const char *outval=NULL;
  
      outval=tester(0);
      printf("0 is %s\n",outval);
      outval=tester(1);
      printf("1 is %s\n",outval);
  
      return EXIT_SUCCESS;
  }
  </code></pre>
  
  <p>I know from <a href="http://c-faq.com/decl/strlitinit.html" rel="nofollow noreferrer">this question in the C FAQ list</a> that <code>"zero"</code> and <code>"non-zero"</code> are (or at least are allowed to be) read-only.  I assume that is why I had to put in the <code>const</code>s before the <code>char*</code> declarations to stop the compiler's warnings about "... discards 'const' qualifier ...".  But while the program gives the expected result of</p>
  
  <blockquote>
    <p>0 is zero</p>
    
    <p>1 is non-zero</p>
  </blockquote>
  
  <p>I also know that <code>tester</code> can not be defined as:</p>
  
  <pre><code>char* tester(int inp)
  {
      char retval[9];
  
      if (inp==0)
          strcpy(retval,"zero");
      else
          strcpy(retval,"non-zero");
  
      return retval;
  }
  </code></pre>
  
  <p>because the array <code>retval</code> must be assumed to be disposed of when <code>tester</code> exits.  </p>
  
  <p>So can I do what I have done in the original code or must I use <code>malloc</code>?</p>