Question regarding Memory Leak

This is a discussion on Question regarding Memory Leak within the C++ Programming forums, part of the General Programming Boards category; Here is the issue, I took a test - online randomized test - for my data structures class. There was ...

  1. #1
    Registered User
    Join Date
    Sep 2007
    Location
    Arizona
    Posts
    164

    Question regarding Memory Leak

    Here is the issue, I took a test - online randomized test - for my data structures class. There was a true-false question on memory leaks. I got it wrong, but reviewed the material in the book and decided to challenge the test (we can do that because there are errors sometimes in the answer key). Anyway, I sent an email to the instructor, a few times, and haven't heard from him.

    Instead of making a pest of myself with him, I decided to post my email to get input from you all. If my understanding and logic are solid, I will pursue it further. If not, I will let the issue die.

    This is the email I sent:
    Q: A class that contains a pointer variable as one of its data members should contain an overloaded assignment operator to prevent memory leaks.

    I struggled with this question for a while. But finally chose false because of what and how the information was presented on pages 158, 159, and 160 regarding destructors and the overloaded assignment operator.

    In the top paragraph of page 159, after discussing how a memory leak occurs on page 158, it says " ...we can put the necessary code in the destructor to ensure that when objectOne goes out of scope, the memory created by the pointer p is deallocated. This is one of the main purposes of including a destructor."

    The bottom of page 159 states the information regarding the assignment operator and avoiding shallow copying of data for classes with a pointer data member, by overloading it. Because shallow copying has two pointers referencing the same data and when one goes out of scope the memory is deallocated but a pointer still points to it. That isn't a memory leak prevented with an overloaded assignment operator, because the memory has been deallocated.

    A memory leak is memory staying allocated without any access to the data held in it. A destructor, with the necessary code, to ensure when an object goes out of scope the memory created by the pointer is deallocated prevents the memory leak.

    I answered: False.

    A destructor that has the necessary code to ensure when an object goes out of scope, the memory created by the pointer is deallocated, is what prevents the memory "leak." The overloaded assignment operator ensures that two objects pointing to the same data, has their own copy of the data, so if one goes out of scope and the memory is deallocated the other object isn't "pointing" at nothing, it is still pointing at its own copy of the data. But the destructor deallocating the memory when the object goes out of scope is what prevents a memory leak.

  2. #2
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Actually, the assignment operator is needed for both purposes. It's certainly true the destructor prevents some memory leaks, but the assignment operator prevents others, in addition to doing a deep copy.

    For example, assume you do this (where MyClass is a poorly-written class that has no assignment operator, and some pointer variable ptr):

    MyClass a, b;
    a = b;

    The assignment does two things:
    1. It does a shallow copy of b.ptr to a.ptr, making both pointers point to the same data, leading to the issue you described,
    2. Causes a memory leak. Can you see how? Hint: What about the memory that used to be pointed at by a.ptr?
    Last edited by Cat; 12-05-2007 at 08:40 PM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,053
    The question is certaintly poorly worded. Just because a class hold a pointer, does not mean that it hold dynamic memory, that it needs to manage. For example, a linked list node might not be responsible for managing the memory it points to; that task would be allocated to the linked list class itself.

    However, assuming that "contains a pointer variable" is ment to imply containing dynamic data, for which the object is responsible, then yes, the assignment operator should be overloaded, or made private.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  4. #4
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,269
    If I were taking the test, I would answer false. Unfortunately, it takes a long time to justify this answer. You practically never need specialized copy constructors or assignment operators. I will happily demonstrate what I mean to anybody wishing to challenge that statement.

    EDIT: As far as this class and this instructor, I'm sorry to say you are probably out of luck. Your run-of-the-mill C++ programmer believes fervently that you DO need assignment operators, copy constructors, try/catch, and a lot of other crap. Unfortunately these people have been blinded to better ways of doing things, but you sure as hell won't convince them otherwise, at least not in just a few minutes' discussion.
    Last edited by brewbuck; 12-05-2007 at 10:06 PM.

  5. #5
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    I would have answered false as well due to how the question was worded.

    Q: A class that contains a pointer variable as one of its data members should contain an overloaded assignment operator to prevent memory leaks.
    This cannot always be true and thus true is not the best answer. Now if it said a pointer that points to allocated memory or memory on the heap within the class then yes I would agree with it since an assignment without an overload would mean two objects use the same memory. Thus when one goes out of scope and deletes the memory, the other class now points to essentially nothing causing a major problem.

    But to say that every class that contains a pointer needs an assignment operator overload is a bit harsh and not applicable in all instances. For instance in Direct3D if you are passing around an IDirect3DDevice9 pointer for each class to use, you cannot re-assign this or recreate this in an assignment operator overload. You could overload assignment but you would not be doing anything but:

    m_pDevice = obj.m_pDevice;

    Which can be done without the overload since this is a simple pointer assignment. Many times a pointer will point to another object and not necessarily memory (well, it's all memory but you know what I'm saying) and it's not always necessary or advised to create a new instance of the object.

    Your run-of-the-mill C++ programmer believes fervently that you DO need assignment operators, copy constructors, try/catch, and a lot of other crap.
    I fail to see how the latter statements have anything to do with the topic at hand nor do I agree that they are somehow inferior to other approaches. try/catch, operator overloading, and copy constructors are very powerful features of C++ and I fail to see how they are evil or lesser than some other method of dealing with the issues they are designed to address.
    Last edited by VirtualAce; 12-05-2007 at 10:24 PM.

  6. #6
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Well it's pretty late, so my brain isn't working at 100% right now, but I don't see how doing a shallow copy would lead to a memory leak?
    Assuming the destructor properly deletes the memory, the only problem I can see is a crash when the same pointer gets deleted twice.

    If it really could lead to a memory leak, can someone give me an example of how and why?

  7. #7
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,269
    Quote Originally Posted by cpjust View Post
    If it really could lead to a memory leak, can someone give me an example of how and why?
    The memory leak comes from the target object of the copy. The pointer value it had before the copy is lost.

  8. #8
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by brewbuck View Post
    The memory leak comes from the target object of the copy. The pointer value it had before the copy is lost.
    Doh! Thanks.
    I think I'll go to bed before I ask any more simple questions.

  9. #9
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    After reading the comments, I think I would vote false on this due to the ambiguity.

    If the object isn't responsible for cleaning up the memory that its member points to, then having an assignment operator to clean up the memory before the copy is more than just simply useless. It would most likely cause blatant errors with your program.

  10. #10
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,269
    Quote Originally Posted by Bubba View Post
    I fail to see how the latter statements have anything to do with the topic at hand nor do I agree that they are somehow inferior to other approaches. try/catch, operator overloading, and copy constructors are very powerful features of C++ and I fail to see how they are evil or lesser than some other method of dealing with the issues they are designed to address.
    So you oppose smart pointers? If you think an assignment operator is "powerful" surely the concept of a pointer which automatically manages deletion must be AMAZING. My methods are simply extensions of that basic idea. Almost ALL behaviors that can be achieved through specialized copy-constructors and assignment operators AS WELL AS try/catch can be implemented by wrapping types in container types which implement those behaviors.

    Seriously, don't you find it a pain to write copy constructors and assignment operators? I do. A little work up front and you completely eliminate the need. If you want examples I'm happy to show you some.

    I have empirical experience which shows that it is NOT necessary to write an assignment operator just because your class holds a pointer to allocated data. Nor is it necessary to use a try/catch just because some object might throw an exception. I realize that it's not obvious. That empirical evidence leads me to answer an unequivocal "false" to this question. It might not be dead-on-topic but it's in the ballpark.
    Last edited by brewbuck; 12-05-2007 at 11:57 PM.

  11. #11
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    The answer can only be false. The sheer fact that a structure has a pointer as one of it's members doesn't even necessarily imply any dynamically allocated memory is even involved. It could be a pointer to a global object. Or it could be dynamically allocated, but another class is responsible for its deletion.

    If true is expected as the answer then intent of the question is obviously that an assignment operator is required to free the dynamically allocated resources held by the object on the left-hand side of the expresion.

    But the question needs to state that the member pointer is to memory that is dynamically allocated, and also that no other parts of the program contain the same pointer anywhere. Perhaps the most cunning way to state both of these is to say that the destructor of this class already deletes the memory pointed to by the member pointer.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  12. #12
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Quote Originally Posted by Bubba
    try/catch, operator overloading, and copy constructors are very powerful features of C++ and I fail to see how they are evil or lesser than some other method of dealing with the issues they are designed to address.
    Quote Originally Posted by brewbuck
    If you think an assignment operator is "powerful" surely the concept of a pointer which automatically manages deletion must be AMAZING.
    Why don't we all just kiss and make up? Assignment operators etc. are excellent ways to deal with "the issues they are designed to address". If you choose to interpret their intended purpose as implementing these high-level primitives you speak of (smart pointers etc.), so be it. I believe Bubba's comment was more in response to your "Never use X!" tone than anything else; so, let's just leave this argument at "absolute statements are frowned upon on this forum."
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,985
    I say false.
    The problem is that it doesn't say a lot of things. Should it need an assignment operator? It all comes down to HOW that memory with that pointer is used. Is it used to link to memory it does not own? Then it would be a design flaw to release it in the destructor (probably) not to mention making a copy of that object in an assignment is questionable.
    That pointer could also just as well not be used as an allocation pointer but a pointer meant for something else. Linked lists are an example of what pointers can be used to without allocating memory. You can also travel through arrays, C-style strings, etc, etc.
    There's just no way it can be true since it depends on the circumstances of the pointer.
    If it's true that it's allocated, then one must also consider - should it actually make a copy of that data? Or should the class being assigned to actually create its own object?
    Or is this a class that simply shouldn't be assigned at all?
    So many variables to ponder on. There's no easy answer on many topics.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    I'd vote true, simply because I understand the intention behind the question, even if it is worded poorly.

    Quote Originally Posted by Bubba
    You could overload assignment but you would not be doing anything but:

    m_pDevice = obj.m_pDevice;
    You'll probably want to AddRef the object, though.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  15. #15
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Quote Originally Posted by brewbuck View Post
    If I were taking the test, I would answer false. Unfortunately, it takes a long time to justify this answer. You practically never need specialized copy constructors or assignment operators.
    While that's true, the methods you speak of would involve refactoring to remove the dumb pointer that's at the heart of the question, and thus you're more or less sidestepping the question rather than answering it

    I guess one example of a time to use the big three would be the PIMPL idiom, as generally you'll want deep-copy semantics for that. You could have deallocation handled by a smart pointer but you'd still need copy/assignment to do the deep copy. I'm not a huge fan of PIMPL though in any event, but it has its uses.
    Last edited by Cat; 12-06-2007 at 01:59 AM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 07:22 AM
  2. Memory Leak Help
    By (TNT) in forum Windows Programming
    Replies: 3
    Last Post: 06-19-2006, 12:22 PM
  3. Memory Leak
    By Berticus in forum C++ Programming
    Replies: 5
    Last Post: 07-20-2005, 06:11 PM
  4. Memory Address of Array Question
    By Zeusbwr in forum C++ Programming
    Replies: 3
    Last Post: 10-24-2004, 10:58 AM
  5. Is it necessary to write a specific memory manager ?
    By Morglum in forum Game Programming
    Replies: 18
    Last Post: 07-01-2002, 02:41 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21