Nico Schlömer
Nico Schlömer

Reputation: 58831

resizing vector of pointers segfaults

I keep hitting this weird std::vector behavior which I can't make any sense of.

Roughly, the code looks like

#include <iostream>
#include <vector>

class MyClass{
public:
  MyClass():
    v_(),
    w_(init_w())
  {};

  ~MyClass()
  {};

  std::vector<int*> init_w()
  {
    v_.resize(4096);
    return v_;
  };
private:
  std::vector<int*> w_;
  std::vector<int*> v_;
};

int main()
{
  MyClass a;
}

Running this gives me a bad segfault at the resize. If a lower value is chosen for the resize instead, the code might not segfault at all.

Update: The problem is that, contrary to what the initializer list indicates, w_ get initialized before v_. Hence, in init_w(), v_ state is undefined. Reverting the order of v_ and w_ in the declarations fixes the problem.

Upvotes: 1

Views: 2079

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124722

The problem is that, contrary to what the initializer list indicates, w_ get initialized before v_

You inferred that to be the case, but in reality it is not. The order of the list is not relevant; the order of declaration in the class is. So, your initialization list should mimic the declaring order if you want to see how the members are actually being initialized.

My question to you is; why are you using a vector of pointers to begin with? Do you realize that you need to delete every element in the list before your object goes out of scope or suffer a memory leak?

Upvotes: 2

Related Questions