简体   繁体   中英

Basic C++ segfault when using new and passing a pointer

Can somebody please explain the segfault here:

class foo
{
  private:
    some_class *test_;


    void init_some_class(some_class*);
    void use_class();
 }

 foo::foo()
 {
     //test_ = new some_class(variables, variables); //THIS WOULD WORK
 }

 void foo::init_some_class(some_class *tmp)
 {
   tmp = new some_class(variables,variables);
 }

 void foo::use_class()
 {
   test_->class_function() //THIS SEGfaults
 }

I would call the funtion via init_some_class(test_); If I use new in the constructor then the test_->class_function() works fine. It only seems to segfault when I use new outside of the class constructor and try and pass the pointer through the function

When you write in init_some class() :

tmp = new some_class(variables,variables);

you are in fact storing the new pointer in the parameter that is passed by value. But this parameter is local to the function and lost as soon as the function returns.

So if you call somewhere init_some class(test_) the value of test_ is transferred to tmp , but the changed tmp remains local to the function. You therefore get a segfault beause test_ remains uninitialized.

Possible solutions:

A simple solution to the described use case could be to pass the parameter by reference:

void foo::init_some_class(some_class *& tmp)  // note the &
{
   tmp = new some_class(variables,variables);
}

With this definition, when calling init_some class(test_) , the original test_ pointer gets modified.

Another solution could be to have the init_some_class() change directly the test_ member. You'd then no longer need a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM