Do pointers to string literals remain valid after a function returns?

后端 未结 4 515
温柔的废话
温柔的废话 2020-11-30 09:48

Is the pointer returned by the following function valid?

const char * bool2str( bool flg )
{
    return flg ? \"Yes\" : \"No\";
}

It works

4条回答
  •  旧时难觅i
    2020-11-30 10:29

    On storage duration:

    2.13.4 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration

    read in conjunction with 3.7.1

    3.7.1.

    All objects which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these objects shall last for the duration of the program (3.6.2, 3.6.3).

    On type:

    Annex C

    Subclause 2.13.4:

    Change: String literals made const The type of a string literal is changed from “array of char ” to “array of const char.” The type of a char16_t string literal is changed from “array of some-integer-type ” to “array of const char16_t.” The type of a char32_t string literal is changed from “array of some-integer-type ” to “array of const char32_- t.” The type of a wide string literal is changed from “array of wchar_t ” to “array of const wchar_t.”

    Rationale: This avoids calling an inappropriate overloaded function, which might expect to be able to modify its argument.

    Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Simple syntactic transformation, because string literals can be converted to char*; (4.2). The most common cases are handled by a new but deprecated standard conversion: char* p = "abc"; // valid in C, deprecated in C++ char* q = expr ? "abc" : "de"; // valid in C, invalid in C++

    How widely used: Programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are probably rare.

    Dynamically allocated (the word 'heap' is never used in context of an area of memory AFAIK in the standard) memory requires a function call that can happen as early as main much after the static memory is allocated.

提交回复
热议问题