c++clifetimestring-literals

What is the lifetime of a string literal returned by a function?


Consider this code:

const char* someFun() {
    // ... some stuff
    return "Some text!!"
}

int main()
{
   { // Block: A
      const char* retStr = someFun();
      // use retStr
   }
}

In the function someFun(), where is "Some text!!" stored (I think it may be in some static area of ROM) and what is its scope lifetime?

Will the memory pointed by retStr be occupied throughout the program or be released once the block A exits?


Solution

  • The C++ Standard does not say where string literals should be stored. It does however guarantee that their lifetime is the lifetime of the program. Your code is therefore valid.