Sign in to follow this  
Show

C++ class object + memory question

Recommended Posts

I have a question regarding objects created in a loop. i've noticed that using the code below that every obj1 created in the loop gets write into the same memory location, so overwrites occurs and the same thing gets added to the list. while (loop 3 times) { int arg1(0); SomeClass obj1(arg1); list.add(obj1); } so i tried while (loop 3 times) { int arg1(0); SomeClass *obj1 = new SomeClass(arg1); list.add(obj1); } this works and gives each obj1 its own memory location. My question is how do i free up the memory before program terminates? since obj1 obviously only points to the last object created. Does the memory gets freed automatically when the program terminates? Thanks for help!

Share this post


Link to post
Share on other sites
Is your list a list of objects or a list of pointers? Do you have any particular reasons for storing pointers, instead of objects, in the list?

Memory is indeed freed when the program exits on most modern operating systems, but it will not be freed during program execution, so any objects allocated will use up memory until the program ends (this might qualify as a memory leak) unless you delete them manually.

Share this post


Link to post
Share on other sites
Quote:
Original post by Show

while (loop 3 times) {
int arg1(0);
SomeClass *obj1 = new SomeClass(arg1);
list.add(obj1);
}
My question is how do i free up the memory before program terminates? since obj1 obviously only points to the last object created.


Look at what exactly you are doing in the above source code and you should come up with an answer to your own question easily: you are adding each pointer to the list, thus all pointers are also available in the list.
So, you can simply iterate over the list and delete each pointer manually using a loop. Depending on your implementation of list, you may actually make this a part of your list's destructor.

HTH

Share this post


Link to post
Share on other sites
Does your list copy the object into it?

If so it is irrelevant if the SomeClass objects are all created at the same spot, as they will be copied correctly (provided you have alowed for a copy ctor if needed ) into the list.

What is the type of list? Is it your own?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this