Question

i've a code that shouldn't work, but it works. Can you tell me why?

#include <iostream>

void f ( int** a, int b ) ;

int main (void) {

    int ** a ;
    a = new int* () ;  

    f(a,5) ;

    std::cout << **a << std::endl ;

    return 1 ;

}

void f ( int** a, int b ) {

    *a = &b ;

}

I declare a pointer to pointer named a, i allocate a pointer to it and then i pass it to f(). The other f() argument is a constant literal, so it is supposed to haven't static memory allocated in main(), ergo it shouldn't exist after f(). Inside f() i assign the memory direction of the local variable b to the pointer to pointer on main copied by f(), then when main() executes f() all local variables should be deleted and then proceed, so a should point to trash, or nothing, but it doesn't and points to 5,value of already deleted b.

What does realy happen? Why this code works?

Était-ce utile?

La solution

It seems like it works, but actualy it doesn't.

*a points to address on the stack.

When you print **a, what is acutaly printed is the content of certain address on the stack. (The address that contained 5 when you call the function f).

However, because the stack doesn't change much according to your code, the value 5 is still written on the certain address so the value 5 is printed. If you would call to other function and then print **a you will probably get different value.

Autres conseils

The memory doesn't get overwritten right away in your case. This is undefined behaviour and it may not behave the same all the time. Each compiler may treat it differently, you may see different results on different platforms or even in release vs debug modes.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top