Scope of (string) literals

前端 未结 7 1159
半阙折子戏
半阙折子戏 2020-11-27 18:13

I always try to avoid to return string literals, because I fear they aren\'t defined outside of the function. But I\'m not sure if this is the case. Let\'s take, for example

相关标签:
7条回答
  • 2020-11-27 18:48

    It's really important to make note of the undefined results that Brian mentioned. Since you have declared the function as returning a const char * type, you should be okay, but on many platforms string literals are placed into a read-only segment in the executable (usually the text segment) and modifying them will cause an access violation on most platforms.

    0 讨论(0)
  • 2020-11-27 18:53

    Yes, that's fine. They live in a global string table.

    0 讨论(0)
  • 2020-11-27 18:55

    I give you an example so that your confusion becomes somewhat clear

    char *f()
    {
    char a[]="SUMIT";
    return a;
    }
    

    this won't work.

    but

    char *f()
    {
    char *a="SUMIT";
    return a;
    }
    

    this works.

    Reason: "SUMIT" is a literal which has a global scope. while the array which is just a sequence of characters {'S','U','M','I',"T''\0'} has a limited scope and it vanishes as soon as the program is returned.

    0 讨论(0)
  • 2020-11-27 18:57

    You actually return a pointer to the zero-terminated string stored in the data section of the executable, an area loaded when you load the program. Just avoid to try and change the characters, it might give unpredictable results...

    0 讨论(0)
  • 2020-11-27 19:04

    This is valid in C (or C++), as others have explained.

    The one thing I can think to watch out for is that if you're using dlls, then the pointer will not remain valid if the dll containing this code is unloaded.

    The C (or C++) standard doesn't understand or take account of loading and unloading code at runtime, so anything which does that will face implementation-defined consequences: in this case the consequence is that the string literal, which is supposed to have static storage duration, appears from the POV of the calling code not to persist for the full duration of the program.

    0 讨论(0)
  • 2020-11-27 19:05

    No, string literals do not have scope, so your code is guaranteed to work across all platforms and compilers. They are stored in your program's binary image, so you can always access them. However, trying to write to them (by casting away the const) will lead to undefined behavior.

    0 讨论(0)
提交回复
热议问题