0
votes
int* g () {
    int j = 2;
    return &j;
}

int main () {
    using namespace std;

    int v = *g();
    //  assert(v == 2);  // Valgrind: Conditional jump or move depends on uninitialised value(s)
}

So, that assert causes a Valgrind error, but I am not too sure what that error means, and why I am not allowed to call assert on that statement.

'v' has been initialized before the assertion, so why is it causing that error?

Thank you in advance.

1
You can't reliably return a pointer to a local variable like that; the variable has been destroyed by the time control returns to the calling function. - Jonathan Leffler
@JonathanLeffler: "Not reliably"? It's instant UB! - Kerrek SB
And UB is unreliable...sometimes it appears to do what you expected, and mostly it doesn't, especially when you're under stress or demonstrating your code, or ... - Jonathan Leffler

1 Answers

3
votes

j was initialized, but became effectively uninitialized as soon as it became illegal to rely on it having any particular value, which happened when it went out of scope.

This code returned a pointer to j:

int* g () {
    int j = 2;
    return &j;}

This code dereferenced that pointer:

int v = *g();

But j no longer exists -- it went out of scope when g returned. You can't dereference a pointer to a variable that no longer exists.