Memory Management
I have previously posted this in the Gapidraw forum but I haven’t had any replies yet – and in any case it’s not really GapiDraw specific, so I thought I'd try here. It’s regarding my game for Smartphone, which I hope to release shortly.
I've been creating memory logs using the code as featured on the ppcstudios website forum.
When I call the function to output the memory usage to file in the InitInstance method, the amount of free memory decreases on successive runs of my program. It's not exactly the same amount every time but tends to vary between 20k-40k. Does this mean I have a memory leak? Obviously I can't tell what my phone is doing in the background but it does seem strange that by simply executing the program, exiting, and executing it again in exactly the same way that I should lose this memory.
From what I understand (which could well be wrong) anything created with the new keyword must be deleted using the delete keyword. I also assume that any global variables just remain in memory for the duration of the program and any local variables only last for the function in which it is defined.
Are there any other general pointers anyone could give me with regards to memory mangagement. I come from a Java background where all this stuff is done for you and I realise that memory management is quite a large area of C++ programming, so any general help would be great.
Thanks in advance.
Be sure to use delete [] when deleting dynamically allocated arrays. I seem to forget that one fairly often and have to keep reminding myself.
Pam
Thanks Pam, I didn't know that.
I don't have any dynamically allocated arrays though.
Are my assumptions in the original post correct - i.e I don't have to worry about anything that is not dynamically allocated?
I only "delete" things that I've created with "new". All of the other stuff is supposed to be taken care of for you.
-John
First and foremost, if memory is being depleted between executions then there must be a different problem. Like your application is hanging and not actually terminating, so there are multiple instances running at once. The OS should free up all memory used by your program when it exits, whether nor not you properly deallocated it within your program.
delete<b>[]</b> is needed specifically when you have an array of C++ classes. That way the destructor of each class instance in the array is called (which may be responsible for deleting additional memory dynamically allocated in the class - if not then it won't matter either way, besides being the difference between good and poor programming practice).
There are many, many, many things you have to "delete", although it is not always apparent that you are freeing memory. Everything from creating windows, opening files, searching for files, to various string routines, must have an appropriate "Close" routine called to free up the memory used by those routines.
The documentation for the routine in question should indicate whether or not a "Close" routine should be called or memory freed up.
Every application uses a Stack, which is a chunk of memory reserved for the application when it executes. That is separate from dynamic memory allocation. The size of the stack is predetermined at link time, so your program will take up that much memory while it is running whether or not it actually uses it. If your program is hanging, or multiple instances are running at once, then each instance could consume significant memory just for its stack alone, independent of dynamically allocated memory.
Also don't forget that the C counterpart to C++'s new / delete is malloc / free.
Dan East
You might be interested in Entrek's CODESNITCH tool. They have a 14-day evaluation version available for download from their website.
More here.
Some clarifications of what Dan wrote.
You need to call delete[] whenever you create an array of anything (not just classes) using new foo[123] syntax.
It is important for class destructors to be called even if there is no memory to be freed, since they could have other important side effects (like updating a usage count).
There are officially (according to the standard) five places a C++ program can store things. I believe they are global/static, function static, auto (i.e. on the stack), heap, and free store. Note that the distinction is made between heap and free store. I believe malloc goes to the heap, and new goes to the free store. However, I also believe in most cases it's actually the same place. I can't find my copy of the standard right now so I can't check this.
Thanks people. I am pretty sure that the program is exiting properly. The app is based around GapiDraw's CGapiApplication so calling the shutdown method should close the app properly.
I think the memory change must be to do with what the phone is doing in the background. I guess that every time the phone performs any action, whether it be running an app or receving a call, various things in the OS are changed - such as most recently used apps, or call history etc. This seems the most likely cause of my memory fluctuations.
With respect to codesnitch - I downloaded the trial version but couldn't get it to work. It seems to corrupt my GapiDraw dll and the OS then complains that the app is not digitally signed. My phone is application unlocked so apps should not require a digital signature. Anyway I've emailed Entrek and I await a response.
In any case thanks very much for all your replies. For someone who's done most of their programming in Java your posts have helped my understanding of memory management in C++ - and that can only be a good thing!!
Hello,
I think that there is a C++ design glitch, that requires after deletion the null, or 0 assignement of memory that was pointed by your object(s).
if you don't mind do:
#define DEL(x) {if(x){delete(x);(x)=0;}}
or
#define DELv(x) {if(x){delete(x);(x)={0};}}
for arrays
The same applies for free()
#define FREE(x) {if(x){free(x);(x)=0;}}
Chris
SpaceManoeuvers,
Is that actually true? I used to do make all my pointers NULL out of habit, but I stopped doing it because I didn't think it made a difference. Are you saying that memory leaks will occur unless you do this?
Nathan
Hello golan_trevize_x,
It seems to be true. Think of delete as a mechanism to delete the pointer, not the actual data stored in it. So there may be carbage.
There may be compilers that correctly implement delete and others that don't. In any case, i do this, just for precaution.
Chris
heap, and free store. Note that the distinction is made between heap and free store. I believe malloc goes to the heap, and new goes to the free store. However, I also believe in most cases it's actually the same place. I can't find my copy of the standard right now so I can't check this.
I think that free store is the other name of heap. Both malloc and new pertain to the same thing.
If you find the text you say, please tell the diference, because everytime i see such mention, the writers refer as this is the same thing.
Chris
Yes but I saw heap and free store distinguished somewhere reputable, either the standard or a book such as Stroustrup or Sutter or Meyers.
I remember reading some discussions (probably on c.l.c++.m) about whether the standard indirectly required the heap and free store to be the same, or to be different. That is, there was no direct requirement, but it may have been implicit in all the other requirements.
Put in plain English, it may be that the standard distinguishes them, but that any conforming implementation must make them the same.
I'm not an expert so I don't know. But I remember reading about the distinction. This is just a nit-picky thing anyways.
You do not have to null out your pointers after deleting what they point to.
If you do, it is not an error to call delete again on a null pointer. It will have no effect.
If you don't, and you call delete again on a non-null pointer that has already had what it pointed to deleted, behaviour is undefined as you have done something wrong.
Could it be that you are deleting an object to which you point, but that object itself isn't deleting other stuff to which it points? That is, are you orphaning memory resources (losing all pointers to them)?
SpaceManeouvres: I think I understand what you are saying, but you're writing is backwards to what you intend to say.
Let's all be clear on this:
The pointer itself has a value. What is pointed to (the data) also has a value.
Let's say the pointer lives on the stack, and the data lives on the heap.
In that case, you want to eventually free the data on the heap by calling delete. You do this by calling delete with the pointer value as argument.
This frees the memory used by the data. It does not clear the actual data. It also does not clear the pointer value.
If you subsequently call delete on that pointer again, you have performed a double deletion which is illegal. Bad things may happen, but it is your fault.
If you don't double delete, you don't have to worry about this.
If you are worried about this, you can clear your pointer value after performing the deletion. Then, you can safely delete it again, because deleting the null pointer is safe and does nothing. You haven't performed a double deletion of the allocated memory in this case.
Either way, the memory which used to hold your data likely still holds the old data, as orphaned garbage. Unless you explicitly cleared it beforehand.
Personally, I wouldn't clear data or pointers. I think that just hides underlying problems (e.g. dangling pointers or double deletion) in my code, and I'd rather fix those underlying problems.
If the pointer is on the stack, the pointer itself will cease to exist when the stack frame is popped. Of course, if you didn't clear it, it also may leave a garbage (pointer) value in memory which you should not be using.
Always be clear (in your thought, if not in your writing) about the difference between the POINTER and THE POINTER'S VALUE and WHAT IS BEING POINTED TO. They are several different things, with their own identity, their own locations, and their own lifetimes.
Basically, you should try to allocate on the stack and only use the heap if you need more flexibility with lifetime. On the stack, things automatically get cleaned up. On the heap, you must clean up manually, exactly once (not zero, not twice). In C++, this means using delete to both destroy the object (thereby perhaps doing other things and destroying other objects) and to reclaim that memory. The only exception is that it is OK to let the program terminate to release all dynamic memory (but this will not run destructors that may do important things).
Please note that you can avoid most of these issues by using the standard auto_ptr template, or boost.org's almost-standard shared_ptr template. Really, they will make your life easier.
Hello mlepage
Sorry not to be clear, but english isn't my native, and writing such an extensive explenation is a pain for me. In any case, what you just write is what i wanted to write the first place.
I just thought that the snippet was intuitive enough.
Nevertheless, this tactic is only for precaution, it has nothing to do with double deletion (althouth it copes with dangling pointers), and is a simple way to RESET memory, without "orphaning memory resources (losing all pointers to them)". (You have orphaning them already by deleting them)
Everytime i do it i say "DELETE & RESET" nothing more.
Chris
ps. If i remember right, the first time i saw this kind of tactic was in Bohem's GC, although i can't confirm it right now.
Guys,
Phew!

Thanks for clearing that up. I agree that I'd rather ensure that my code doesn't have double-deletes.
re: stack vs heap, I use the heap for all my objects, and only use the stack for primitives and structs.
Nathan