idgregorio
Programmer
Hi,
The following code throws a segmentation fault at runtime and I can't figure out why. Perhaps somebody can help. The code defines a class X whose constructor takes an integer n and creates dinamically an array of n vector<int>. The destructor will free this memory. The class appears to work well, here it is:
#include <iostream>
#include <vector>
using namespace std;
class X{
public:
X(int n = 0);
~X();
private:
vector<int>* a_;
int n_;
};
X::X(int n): n_{
a_ = new vector<int>[n_](n_);
}
X::~X(){
delete[] a_;
a_ = NULL;}
Now I run into problems when I exercise my class in main(), more precisely, when I call the default copy constructor. The funny thing is that if do
int main(){
X x(5); // array of 5 elements, in fact the
// program works fine for 1,2,3 and 4
X y = x;
return 0;}
everything works fine but if I do
int main(){
X x(6); // 6 elements (same for 7, 8, ...)
X y = x;
return 0;}
I get the following error (from the vector destructor) at runtime:
Program received signal SIGSEGV, Segmentation fault.
0x08048b48 in ~vector (this=0x9b956e0) at stl_vector.h:375
A final note is that I'm using g++ and stl from GNU. Is it my fault that this program doesn't work?
Best regards.
The following code throws a segmentation fault at runtime and I can't figure out why. Perhaps somebody can help. The code defines a class X whose constructor takes an integer n and creates dinamically an array of n vector<int>. The destructor will free this memory. The class appears to work well, here it is:
#include <iostream>
#include <vector>
using namespace std;
class X{
public:
X(int n = 0);
~X();
private:
vector<int>* a_;
int n_;
};
X::X(int n): n_{
a_ = new vector<int>[n_](n_);
}
X::~X(){
delete[] a_;
a_ = NULL;}
Now I run into problems when I exercise my class in main(), more precisely, when I call the default copy constructor. The funny thing is that if do
int main(){
X x(5); // array of 5 elements, in fact the
// program works fine for 1,2,3 and 4
X y = x;
return 0;}
everything works fine but if I do
int main(){
X x(6); // 6 elements (same for 7, 8, ...)
X y = x;
return 0;}
I get the following error (from the vector destructor) at runtime:
Program received signal SIGSEGV, Segmentation fault.
0x08048b48 in ~vector (this=0x9b956e0) at stl_vector.h:375
A final note is that I'm using g++ and stl from GNU. Is it my fault that this program doesn't work?
Best regards.