Edit: Sorry I'm a total idiot...just figured it out after posting this thread. I was apparently totally blind...if you're bored, I'll leave the post as is and you find the problem and can laugh at me. Otherwise you should probably go on your merry way. :p
Note: Please ignore all the "this" that is floating around my code. I know it's not necessary and most C++ programmers seem to leave it off, but it is helping make my adjustment from Python to C++ a little easier. (Besides it seems irrelevant to my question...though correct me if I'm wrong!)
I'm going through a (very) basic implementation of vector<double> like class and am running into trouble. It compiles fine with 'g++ -g' on 64bit Linux (Linux Mint...mostly like Ubuntu), but it segfaults when executed. Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
class Vector {
public:
Vector(int s);
~Vector();
Vector(const Vector& a);
Vector& operator=(const Vector& a);
double& operator[](int i);
private:
double* elem;
int sz;
};
Vector::Vector(int s) {
this->elem = new double[s];
this->sz = s;
}
Vector::~Vector() {
delete[] this->elem;
}
Vector::Vector(const Vector& a) {
this->elem = new double[a.sz];
this->sz = sz;
for (int i = 0; i < sz; ++i) {
this->elem[i] = a.elem[i];
}
}
Vector& Vector::operator=(const Vector& a) {
delete[] this->elem;
this->elem = new double[a.sz];
// HERE IS WHERE ERROR HAPPENS AT RUNTIME
this->sz = a.sz;
for (int i = 0; i < a.sz; ++i) {
this->elem[i] = a.elem[i];
}
return *this;
}
double& Vector::operator[](int i) {
return this->elem[i];
}
int main() {
const int size = 10;
Vector v(size);
for (int i = 0; i < size; ++i) {
v[i] = i;
}
Vector w = v;
return 0;
}
|
I've gone through the debugger in gdb and the problem line is the one below the line marked in the code with "HERE IS WHERE ERROR HAPPENS AT RUNTIME". (**Edit: Sorry...the error technically happens later...what I mean is that this is where the source of the error occurs...) What happens is that that line essentially does nothing. Before the line is executed this->sz is set to 4195936 (which I presume is a default trash value), but after that line it remains the same. In fact, if I look at the source code as shown by gdb (i.e. pressing 'l' at that line), it shows the following:
1 2 3 4 5 6 7 8
|
25 Vector::Vector(const Vector& a) {
26 this->elem = new double[a.sz];
27 // HERE IS WHERE ERROR HAPPENS AT RUNTIME
28 this->sz = sz;
29
30 for (int i = 0; i < sz; ++i) {
31 this->elem[i] = a.elem[i];
32 }
|
As you see on line 28, it is changing a.sz to sz (which is certainly wrong, since sz would refer to this->sz which I _don't_ want).
Is g++ somehow optimizing away a.sz for some reason that I don't understand? (I.e. because I'm doing something illegal by the language?)
Thanks for any help you can provide.