3
votes
const char* str ="Hello World!"
str = "HELLO!"

In this code, will the string "Hello World!" be erased from memory or will it be left alone?

2
Have you checked whether that code compiles?Drew Dormann
From a standard perspective, string literals have static storage duration (which means they exist throughout program execution) and cannot be modified by a program that has no diagnosable errors and does not have undefined behaviour. Of course, there is also the "what if" rule - which means that, in your code, the literal "Hello World!" can be optimised out of existence - which says that any transformations are possible, as long as observable behaviour (i.e. output) is unchanged.Peter
@DrewDormann - The code (assuming they are two consecutive lines in a function, and semi-colons are placed at the end of each line) has no diagnosable errors. str is a pointer to const char, so can be reassigned (but str cannot be used to change the data that str points at - e.g. it cannot be used to overwrite a string literal).Peter
@Peter -- just so you don't start a trend, the "what if" rule is actually the "as if" rule. <g>Pete Becker
Thanks @PeteBecker - I wasn't trying to start a trend. Simply typed too fast.Peter

2 Answers

7
votes

This is not specified by the C++ standard. Your compiler can do whatever it wishes here, including not even storing the original string in the first place, and effectively compiling the following code only:

const char* str = "HELLO!"

Your compiler can prove that performing this optimization has no observable effects, and the C++ standard allows C++ compilers to implement any optimization that has no observable effects.

So what happens here depends entirely on your C++ compiler.

2
votes

In general, string constants tend to be in the global data section, and aren't "freed" until the program ends.

You can see this here: https://godbolt.org/z/a3TbjTba1

String literals, according to [lex.string]/14 are:

Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above