Wednesday, January 18, 2006

Ummm.... I forget

As i mentioned before, memory on a console is a precious commodity. it is up to the programmer to ensure that any memory they have allocated "dynamically" is cleaned up - the computer doesn't know when you are finished with it. Failure to do so results in a memory leak.

Today i updated Steve's PS2 memory leak tracking code to work on the PC build of the game, hopefully to make finding memory leaks a bit more painless. Essentially what Steve's code does is store the return address of the new call, a pointer to the allocated memory and a bunch of other data (amount allocated etc) in a list. Then, whenever the memory is deallocated it is removed from the list.

So, to find a memory leak we just dump the contents on the list - anything left on it is, at the point of the dump, a leak. Of course it's not 100% accurate as you may have allocated memory during the time of tracking the allocations which isn't supposed to have been deallocated. But usually it's pretty easy to tell which one is which.

So here's some technical bits. The key to the whole technique is knowing where the new call is made (new is the function used to get a chunk of memory, if you don't know). So we need to get the point at which function x calls new, and we can do this by looking at the stack. To cut a long story short you need two incredibly complex lines of assembler:
mov eax, [ebp+4]
mov ReturnAddr, eax
you need ebp+4 because at this point ebp points to the calling function's base pointer. This all works according to the __cdecl calling convention. This is a good reference for calling conventions and what they mean and what they do.

I intended this blog to be reasonably non-technical / jargony and to require little previous knowledge about the subject, but this was just quite interesting so i thought i'd share it.

1 Comments:

Blogger cliff said...

in my day we had to use 6 punch cards to do the same thing lad.

8:28 PM  

Post a Comment

<< Home