c++ – What are hanging pointers, what is their danger?

Question:

Why do these kinds of problems appear?

Answer:

char* f()
{
    char s[100];
    // страшное вычисление s
    return s;
}

Represented? call char * s = f(); . Fine? seems Yes.

But when we start using this pointer – that char s[100]; from a function long ago can be overwritten by something else (this memory is allocated on the stack only for the duration of the function ). And we get a dangling pointer – i.e. it exists and even points somewhere… Only there can be anything.

Or –

s = malloc(...);
....
free(s);

The value of s remains – free does not change it, but it points to memory that is freed, can be re-allocated, overwritten … or, for example, deleted again.

Is that clearer?

Scroll to Top