-
traping leaking memory
hi again. again on the subject of dynamic memory allocation for arrays of strings, or whatever, is there any c function or any other way in general that catches memory leaks or tell how much mem is used at any point (i asume that if i make a log file with the free mem at regular intervals it may be possible to identify memory leaks)?
in general, how can i see the mem my prog uses at any time?
moreover, is there any trick to imitate destructors in c?
i'm asking this after realising that i was forgeting to free the mem i got from malloc...
thanks
null
-
When you dynamically allocate memory, you always have to remember to deallocate it. That's one of the problems with C, if you forget then you have a memory leak and there's no way to check for it.
-
Little tool
Hi,
well there is one little thing you could do... Write a little program that counts the number of 'malloc' and 'new' statements in your sourcefiles and of course the number of 'free' and 'delete' statements.
Of course there can still be memory leaks and the programm might be confused in loops ( advanced version you also check loops, but it's realy tricky I think ), but might be worth a try ;) It's a nice practice task for newcomers, too. And it's something you can later really use ... maybe :)
Greetings
cody
-
When you dynamically allocate memory you should try to free that memory in the same function that you defined an instance of the object. This does not always have to be done however there are several situations where you can otherwise run into problems, I'm not going to recite them because I'd have to research that, but I have come across these situations and read about them. After you free memory set the pointer to NULL because if it is accidently deleted twice than it is safe to do so while it is pointing to NULL but not otherwise. It is also safe I believe to dereference a NULL pointer.
-
two things I usually do when I programme in C to detect/avoid memleak.
1) Use TOP utility (if you are using Unix), if the program leaks memory, the 'size' column will keep on increasing as you execute the mem leak functions.
2) Modularise code into functions and reuse the functions whenever possible. All you need to do is to ensure that the function is not leaky.
Good luck
-
> i'm asking this after realising that i was forgeting to free the mem i got from malloc...
A sort of tip.
As soon as you've finished writing your malloc code, break off and write the matching free code.
I used to do the same thing with writing {}, "" and () pairs, until I got an editor which does some of them for me.
There are $$$ tools like boundschecker and purify which help with this task (finding where its all gone wrong that is).