Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char* scope inside C++ containers

With the following:

#include <set>

std::set<const char *> global = std::set<const char *>();
void x() {
    const char *c = "a";
    const char *d = "b";

    global.insert(c);
    global.insert(d);
}

int main() {
    x();
    for (std::set<const char *>::const_iterator iter=global.begin(), end=global.end(); iter!=end; ++iter) {
        printf("%s\n", *iter);
    }

    return 0;
}

In the end, as expected, I receive a and b printed.

Yet, is there any guarantee that, for example, if that set was part of a bozo object, that as the set they'd last until the end of bozo's lifetime? Or would I have to strdup the strings to be sure?

like image 561
Matoe Avatar asked Feb 19 '23 01:02

Matoe


1 Answers

You're totally fine because string literals have static storage duration. That is, the string will be around in memory for the duration of the program. However, it would not be okay if you were to have declared your c and d as arrays like so:

const char c[] = "a";
const char d[] = "b";

This is because when an array is initialised with a string literal, the characters from the literal are copied into the array. That array has automatic storage duration, so the contents will be destroyed at the end of the function x. If you still did global.insert(c), you would be pushing in a pointer to the first element of the c array, but that array won't exist for much longer.

Here's some standard quotes. First, §2.14.5/8:

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

And now the definition of static storage duration (§3.7.1/1):

All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3).

like image 190
Joseph Mansfield Avatar answered Mar 06 '23 22:03

Joseph Mansfield