Search code examples
cstringreturnstring-literalsstorage-duration

Can a static c function return a local char array?


In zflog library I saw this code

static char* lvl_char(const int lvl)
{
    switch (lvl)
    {
    case ZF_LOG_VERBOSE:
        return "VERBOSE\0";
    case ZF_LOG_DEBUG:
        return "DEBUG\0";
    case ZF_LOG_INFO:
        return "INFO\0";
    case ZF_LOG_WARN:
        return "WARN\0";
    case ZF_LOG_ERROR:
        return "ERROR\0";
    case ZF_LOG_FATAL:
        return "FATAL\0";
    default:
        ASSERT_UNREACHABLE("Bad log level");
        return "?\0";
    }
}

which seemed odd to me. Can we really return a local c string from static functions?


Solution

  • You are wrong, the returned pointer is not pointing to a local char array, but to a string literal, that is static for the process.

    From c-standard

    6.4.5 String literals

    Sematics

    In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.78) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.[...]

    Emèphasis mine