Foaly
Foaly

Reputation: 597

SIGSEGV when trying to acces member of pointer after it was filled by function

The answer is probably stupidly easy, but I have stared at this code for quiet a while now and I simply can't find the solution.

Here is my problem. I have a pointer to a base class. Then I call a function to find an element in a vector of objects derived from that class. The pointer is passed as a parameter and filled with the found object. If I try to read a member variable of what the pointer points to I get a SIGSEV.

This is the code:

Base* control;
if(findControlByName("aName", control)) {
    std::cout << control->name << std::endl;  // SIGSEV happens here
}

//...

bool findControlByName(std::string name, Base* control) {
    for(size_t i = 0; i < controls.size(); i++) {
        if(controls[i]->name == name) {
            control = controls[i];
            std::cout << control->name; // this works
            return true;
        }
    }
    return false;
}

How do I do this properly?

Upvotes: 0

Views: 259

Answers (1)

E. Moffat
E. Moffat

Reputation: 3288

To elaborate on my above comment, when you assign a value to a pointer parameter in a function, that value is local to the scope of the function, just like any other parameter that is passed by value. Assigning a value to the parameter in the scope of the function does not change it outside the scope of that function unless it is passed by reference.

An example:

void someFunc(int * x)
{
  static int my_static = 5;
  x = &my_static;
}
void someFunc2(int * &x)
{
  static int my_static_2 = 7;
  x = &my_static_2;
}

//somewhere else:
int * ptr;
someFunc(ptr);
//ptr is unchanged/still uninitialized
someFunc2(ptr);
//ptr points to my_static_2

If the signature of someFunc is changed to take a reference parameter, the parameter will be passed by reference instead of passed by value.

Upvotes: 2

Related Questions