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


can please explain 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 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 call funtion via init_some_class(test_); if use new in constructor test_->class_function() works fine. seems segfault when use new outside of class constructor , try , pass pointer through function

when write in init_some class() :

tmp = new some_class(variables,variables); 

you in fact storing new pointer in parameter passed value. parameter local function , lost function returns.

so if call somewhere init_some class(test_) value of test_ transferred tmp, changed tmp remains local function. therefore segfault beause test_ remains uninitialized.

possible solutions:

a simple solution described use case pass parameter reference:

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

with definition, when calling init_some class(test_), original test_ pointer gets modified.

another solution have init_some_class() change directly test_ member. you'd no longer need parameter.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -