language: C++ 4.7.2 (gcc-4.7.2)
date: 609 days 23 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
 
int* return_dangling_p()
{
        int x = 1;
        return &x;  // warning: address of local variable 'x' returned
}
 
void some_func()
{
    int x = 2;
}
 
int main(int argc, char** argv)
{
    //  UB 1
    int* p = return_dangling_p();
    std::cout << *p;               // 1
    some_func();
    std::cout << *p;               // 2, some_func() wrote over the memory
 
    // UB 2
    if (true) {
        int x = 3;
        p = &x;     // why does compiler not warn about this?
    }
    std::cout << *p;    // 3
    if (true) {
        int x = 4;    
    }
    std::cout << *p;    // 3, why not 4?
 
    return 0;
}
prog.cpp: In function ‘int* return_dangling_p()’:
prog.cpp:5: warning: address of local variable ‘x’ returned
prog.cpp: In function ‘void some_func()’:
prog.cpp:11: warning: unused variable ‘x’
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:29: warning: unused variable ‘x’