0

The problem occurs where I am using operator+ to overload the + operator to add 2 lists together (question asks to end when first list ends if the lengths are different). everything after delete_position() was written by me, the functions above and the main() are provided by the prof.

Alex A
  • 19
  • 2
  • *Here is my code, it all works up* -- No it doesn't. `/*while (head != NULL) { delete_first(); }*/` -- Why is this commented out? Your assignment operator for `List` is leaking memory like a sieve. – PaulMcKenzie Nov 30 '18 at 04:42
  • Since the copy semantics are broken, you need to fix that first before even considering writing functions such as `operator +` that return by value. – PaulMcKenzie Nov 30 '18 at 04:54

1 Answers1

3

One obvious error I see is in the function operator+(List& a, List& b):

Node* tempA = new Node;
Node* tempB = new Node;
tempA = &a.getHead();
tempB = &b.getHead();

You are allocating memory to tempA and tempB first using new and then assigning them to some other addresses.

This will result in:

  • A memory leak because you will not be able to delete the memory allocated using new.
  • Taking the address of a temporary. What you get from a.getHead() and b.getHead() are temporaries.

In fact, compilers like GCC and Clang will not compile this and will emit an error stating something like this:

error: taking the address of a temporary object of type 'Node' [-Waddress-of-temporary]
    tempB = &b.getHead();

Also as @PaulMcKenzie points out, take a look at your copy constructor. Since your class has pointers, you should be careful about the way you copy the data. Read this question and its answers about the proper way to implement the copy* functions.

P.W
  • 26,289
  • 6
  • 39
  • 76
  • Overall, the entire copy semantics for the `List` class is broken. The `operator +` should have only been implemented once the copy semantics for `List` are working properly. – PaulMcKenzie Nov 30 '18 at 04:52
  • @PaulMcKenzie: Updated the answer with input from your comment. – P.W Nov 30 '18 at 05:01
  • I made all these changes, thank you. I am new to c++ and obviously pointers and memory are the hardest topics coming from languages like Java and Ruby. While these changes improved my code, and I think I fixed my copy constructor, I am still having trouble with the final + operator, which must be implemented as a free operator. Do you have any suggestions? I don't know how to avoid using a temporary object in this situation. Thank You – Alex A Dec 01 '18 at 20:22
  • @AlexA: May I know why you have removed the code from the question? Without it, the comments or the answer would not seem relevant to those who look at it later. And without the code, it would be difficult to help you as well. – P.W Dec 03 '18 at 05:13