Segmentation Fault on Delete []

Pages: 12
Why do you need an assignment operator and copy constructor at all? You marked them as private and unimplemented and your program compiled. You should leave them that way. That's a sign that they are not used.

Put some debugging output in your constructor and destructor. Write out the pointer values as they are being created & deleted. Then check that output and verify that you are deleting the proper pointers once and only once.

Just noticed something though. Your default constructor does not have a member initialization list. If you default construct a PriceFeed, your are going to have uninitialized members. That will lead to seg faults too.
Your assignment operator is wrong. It should look almost identical to that of the copy constructor.
To PanGalactic
First Paragraph I did just that. I marked the assignment operator and copy constructor as private and commented out their implementation. Problem continues

Second Paragraph Interesting results. I loaded some data into it - printed okay. Then I attempted to print after deleting the object(s). The program seg faults not at the delete line but NOW at the lines for printing to cout (it prints the very first iteration and then segfaults). Bizarre.

Third paragraph How do I fix the problem in the default constructor? This may fix the overall problem.


To jsmith
Does the assignment operator need to allocate more space on the heap? I thought that spaces exists for the other object (when we create it) and you simply need to change the values stored in it to that of the values in the existing object "rhs". Is this right or do I need to allocate space on the heap inside the assignment operator?
Last edited on
Mmm, that's another problem.

Your default constructor does not initialize the pointer (or any data member, for that matter).

operator= should free any memory used by the object currently and then make a deep copy
of the rhs.

EDIT: for example:

1
2
3
4
5
6
7
8
9
10
class Foo {
  public:
     Foo() : ptr() {}  // Init the pointer to null
    Foo( const Foo& rhs ) : ptr( new int )
      { *ptr = *rhs.ptr; }
    Foo& operator=( const Foo& rhs )
      { delete ptr; ptr = new int; *ptr = *rhs.ptr; return *this; }
  private:
     int* ptr;
};


Really bad example, but to illustrate the point.

Last edited on
jsmith Thanks for the help! :D

I corrected the assignment operator using your toy example.

I fixed the default constructor to look somewhat like the constructor that takes a stream, int, int and the segmentation fault is gone!!!

helios, PanGalactic, and jsmith: Thank you so much for your help!
Next time, use a vector. :-)
Topic archived. No new replies allowed.
Pages: 12