0

I'v got question when I practiced section 5.8(page 113) of K & R The C Programming Language.

original source code is here

/* month_name: return name of n-th month */
char *month_name(int n)
{
    static char *name[] = {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };
    return (n < 1 || n > 12) ? name[0] : name[n];
}

And I already know that we can't return local variable's pointer because it's from stack and it will be destroyed(?) after function return. But in this example they use static to remain that variable.

The question is "Why they still work after I delete static notation".

I changed code to

/* month_name: return name of n-th month */
char *month_name(int n)
{
    char *name[] = {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };
    return (n < 1 || n > 12) ? name[0] : name[n];
}

and they still work very well.

BUT. if I return name instead of name[n], it doesn't work as I expected.

Why does it work?

1 Answer 1

3

It still works because the array contains pointers to string literals. String literals have static storage duration even if the array the holds their addresses doesn't.

In fact an optimizing compiler should wise up to the fact, and produce identical code in both cases.

When you return name however, the same rules that you noted apply. So you get undefined behavior. Although unless you change the return type of the function, then returning name shouldn't compile, since char* and char** are incompatible types.

Sign up to request clarification or add additional context in comments.

4 Comments

If there is no pointers to string literals, is it still remain in static storage? How can free the memory?
@ScottLee - If the pointer aren't to string literals (or other strings with static storage duration) then the usual caveats about memory management apply, yes. How to free depends on how they are allocated, and even then it's tricky.
The compiler could optimise out the storage of the string literals if it knows they can never be used.
@IanAbbott - Indeed. But since the OP noted it "works", I think it's safe to say the function is called, and a decent compiler won't do that even when aggressively optimizing (unless all the calls were removed, of course).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.