0

What is the lifespan of the string literals "zero" and "non-zero" in the following program?

#include <stdlib.h>
#include <stdio.h>

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;
}

I know from this question in the C FAQ list that "zero" and "non-zero" are (or at least are allowed to be) read-only. I assume that is why I had to put in the consts before the char* declarations to stop the compiler's warnings about "... discards 'const' qualifier ...". But while the program gives the expected result of

0 is zero

1 is non-zero

I also know that tester can not be defined as:

char* tester(int inp)
{
    char retval[9];

    if (inp==0)
        strcpy(retval,"zero");
    else
        strcpy(retval,"non-zero");

    return retval;
}

because the array retval must be assumed to be disposed of when tester exits.

So can I do what I have done in the original code or must I use malloc?

fagricipni
  • 927
  • 1
  • 7
  • 9

1 Answers1

1

String literals have static storage duration (i.e. their lifetime is the execution time of the program).

See §6.4.5/6 of the C standard.

rici
  • 234,347
  • 28
  • 237
  • 341