LoginSignup
2
0

More than 5 years have passed since last update.

[Hangout] Stack, Heap, boost::xxx

Posted at

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

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0