?
Solved

deallocating memory with delete

Posted on 2004-11-23
4
Medium Priority
?
243 Views
Last Modified: 2010-04-01
Code snipet:
class foo {
public:
         foo() {var=new double [1000];}
         ~foo() {delete [] var;}
         double * var;
};
int main() {
         foo *a;
         a = new foo;
         delete [] foo;
         return 0;
}

I know that the memory allocated to the pointer "a" is released by delete, but what about "var" does the compile automatically know to release it since it is inside the class or do I need to do it.
0
Comment
Question by:BigLobowski
  • 2
  • 2
4 Comments
 
LVL 5

Expert Comment

by:ddunlea
ID: 12660339
Hi BigLobowski,

You need to change "delete[] foo" to "delete foo" as it was created with "new" and not "new ... [...]"

When you delete a, it calls the destructor of a which in turn deletes var.
0
 
LVL 8

Accepted Solution

by:
AaronReams earned 1000 total points
ID: 12660537
hi there,

you need to delete the object not the class.

delete [] foo;

should be

delete a;

also, when you delete "a", the destructor of "a" will be called before "a" is deallocated.  that is where you need to delete "var", as you have correctly.

cheers,
aaron
0
 
LVL 5

Expert Comment

by:ddunlea
ID: 12660547
Oops. Should've spotted that bit. It's clearly past my bedtime.
0
 
LVL 8

Expert Comment

by:AaronReams
ID: 12660561
no worries.  those late nights will get the best of anyone.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
Suggested Courses

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question