mercredi 30 septembre 2015

const char * value lifetime

I am trying to understand how and when the string pointed to by const char * gets deallocated.

Consider:

const char **p = nullptr;

{
    const char *t = "test";
    p = &t;
}

cout << *p;

After leaving the inner scope I would expect p to be a dangling pointer to const char *. However in my tests it is not. That would imply that the value of t actually continues to be valid and accessible even after t gets out of scope.

It could be due to prolonging the lifetime of the temporary by binding it to const reference. But I do no such thing and even by saving the reference to t in a member variable and printing the value from different function later still gives me its correct value.

class CStringTest
{
public:
    void test1()
    { 
        const char *t = "test";
        m_P = &t;
        test2();
    }

    void test2() 
    { 
        cout << *m_P;
    }

private:
    const char **m_P = nullptr;
};

So what is the lifetime of the t's value here? I would say I am invoking undefined behaviour by dereferencing a pointer to a value of a variable that went out of scope. But it works every time so I think that is not the case.

When trying some other type like QString:

QString *p = nullptr;

{
    QString str = "test";
    p = &str;
}

cout << *p;

the code always prints the value correctly too even though it should not. str went out of scope with its value and I have not prolonged its lifetime by binding it to const reference either.

Interestingly the class example with QString behaves as I would expect and test2() prints gibberish because the value indeed went out of scope and m_P became dangling pointer.

So what is the actual lifetime of const char *'s value?

Aucun commentaire:

Enregistrer un commentaire