Either way there are no memory leaks: every string literal gets its own piece of memory that is cleaned up on program termination; return to const char* returns a pointer to a literal's piece of memory (knowing you cannot alter it); and return to a string makes a copy into a string object existing in the caller's code ...
You can safely return C strings from a function in at least these ways: const char* to a string literal. It can't be modified and must not be freed by caller.
The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character. A null character (represented by the \0 escape sequence) is automatically appended to, and marks the end of, each string literal.
A string is a sequence of characters. The literal value for a string is written by surrounding the value with quotes or apostrophes. There are several variations to provide some additional features. Basic String.
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.
The "Some text!!"
does not have a scope. Scope is a property of a named entity. More precisely, it is a property of the name itself. "Some text!!"
is a nameless object - a string literal. It has no name, and therefore any discussions about its "scope" make no sense whatsoever. It has no scope.
What you seem to be asking about is not scope. It is lifetime or storage duration of "Some text!!"
. String literals in C/C++ have static storage duration, meaning that they live "forever", i.e. as long as the program runs. So, the memory occupied by "Some text!!"
is never released.
Just keep in mind (as a side note) that string literals are non-modifyable objects. It is illegal to write into that memory.
String will be stored statically in special (usually read-only on modern OS) section of the program binary. Its memory is not allocated (individually for the string, only for total section while loading it to memory) and will not be deallocated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With