Discussion:
Assignment 2: Memory Leaks, Do We Not Care?
(too old to reply)
Brian Attwell
2010-05-31 04:51:20 UTC
Permalink
Assignment 2: Memory Leaks, Do We Care?

I'm confused about how we can return references to non-constant objects from
the const functions in Date.h. Here are my assumptions about Date.cpp:
1) We shouldn't return references to local objects
2) We shouldn't return non-const references to static objects, since we
would need an infinite number of static objects lying around.
-->For example: if we only had one static todaysDate object, then I could
change todays date by typing "Date::today() = Date(1, "May", 1900)"
3) We shouldn't return references to dynamically allocated objects, since
programmers shouldn't be expected to delete objects that are returned by
reference.

I feel like I must be missing something. It seems that both reference
versions of Date.o return references to dynamic memory. I say this because
the following line executes fine: "delete &(Date::today())", whereas
attempting this on a reference to auto Date or static Date results in a core
dump.

So, is there a method to ensure deletion of referenced dynamic memory, do we
not care about memory leaks or am I misunderstanding the situation
completely?

I'd really appreciate any clarification,
Thanks, Brian A.
Joanne Atlee
2010-05-31 06:31:11 UTC
Permalink
Hi Brian,
No, you are not missing anything.

I tried to design this assignment so that you would get more practice
with pointers and references, but you are correct that the result is a
bad ADT design -- it puts too much responsibility on the client
programmer to know which Dates need to be deleted by the client code.

I've modified the Date.h so that the methods that return new objects do
so by value (i.e., return type Date) rather than by reference.

Sorry for the confusion.

Jo
Post by Brian Attwell
Assignment 2: Memory Leaks, Do We Care?
I'm confused about how we can return references to non-constant objects from
1) We shouldn't return references to local objects
2) We shouldn't return non-const references to static objects, since we
would need an infinite number of static objects lying around.
-->For example: if we only had one static todaysDate object, then I could
change todays date by typing "Date::today() = Date(1, "May", 1900)"
3) We shouldn't return references to dynamically allocated objects, since
programmers shouldn't be expected to delete objects that are returned by
reference.
I feel like I must be missing something. It seems that both reference
versions of Date.o return references to dynamic memory. I say this because
the following line executes fine: "delete &(Date::today())", whereas
attempting this on a reference to auto Date or static Date results in a core
dump.
So, is there a method to ensure deletion of referenced dynamic memory, do we
not care about memory leaks or am I misunderstanding the situation
completely?
I'd really appreciate any clarification,
Thanks, Brian A.
Loading...