cannot resize c++ std::vector that's a member variable of a class

code (simplified version)

(part of) the class definition:

struct foo {
    std::vector<int> data;
    foo(int a=0):data(a+1,0) {}
    void resize(int a) {
        data.resize(a+1,0);
    }
}

The a+1 part is because I want the data to be 1-indexed to simplify some operations.

in global scope:

int k;
foo bar;

in main function:

std::cin>>k;
bar.resize(k);

Later in the main function, there is a call to another member function (in foo) that accesses the data, causing a segmentation fault (segsegv).

After debugging, I found that data.size() returns 0. Which is very unexpected.

After a very long session of debugging, I feel very confident that the problem is with the resizeing, which shouldn't cause any problems (it's from the standard library, after all!).

P.S. Don't accuse me for putting anything in global scope or giving public access to class members. I'm not writing any "real" program, because I'm just practicing for a programming competition.

Upvotes: 1

Views: 2131

Answers (2)

wich
wich

Reputation: 17157

The following works fine for me

#include <vector>
#include <cstdlib>

struct foo {
  std::vector<int> data;
  explicit foo(int a=0) : data(a+1, 0) {}
  void resize(int a) {
    data.resize(a+1, 0);
  }
};

int main() {
  foo test_foo(1);

  for (size_t i = 0; i < 1000; ++i) {
    int a = std::rand() % 65536;
    test_foo.resize(a);
    if (test_foo.data.size() != a + 1)
      return 1;
  }

  return 0;
}

Upvotes: 1

NPE
NPE

Reputation: 500673

After a very long session of debugging, I feel very confident that the problem is with the resize

It is almost certain that:

  1. The issue doesn't have anything to do with resize().
  2. You have a memory-related bug somewhere (double delete, uninitialized/dangling pointer, buffer overrun etc).

The thing with memory-related bugs is that they can be completely symptomless until well after the buggy code has done the damage.

My recommendation would be to run your program under valgrind (or at least show us an SSCCE that doesn't work for you).

Upvotes: 5

Related Questions