Alex Rivera | Logout

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

Asked 2010-04-05T17:32:31.673
37

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?

Edit
Report

1 Answer

55

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.

answered 2010-04-05T17:37:35.843

Your Answer