More than 1 year has passed since last update.

Stack

stack.cpp
int* stack_a(){
    int *x;
    return x;
}

int main()
{   
    std::cout << *stack_a() << std::endl;
}

output

[1]    2595 segmentation fault  ./a.out

How can we make it works?

Heap

Easiest way is to just use heap memory. But in practice you should do consider recursive algorithm which is able to keep value.

heap.cpp
int* heap_a(){
    int *x = new int;
    return x;
}

int main()
{   
    std::cout << *heap_a() << std::endl;
}

output

0

boost::scoped_ptr

int* scoped_ptr(){
    boost::scoped_ptr<int> x;
    return x;
}

int main()
{
    std::cout << *scoped_ptr() << std::endl;
}

equality to stack_a