Finding memory leaks with OS X


The UNIX standard library provides the malloc() and free() routines to dynamically allocate and free memory. These routines allow developers to increase and decrease memory (the programs heap) as needed, which allows the process to increase or decrease memory consumption as demand increases or decreases. This works great when care is taken to free memory that is no longer needed, but issues (e.g., memory leaks) can occur if memory is allocated and never free()‘ed. If you are using OS X, you can use the leaks(1) command to check a program or process for memory leaks:

$ cat test.c


#include <stdlib.h>

int main(int argc, char**argv)
{
void *foo;
char *bar = "this is a string";

foo = (void *)malloc(128);

foo = bar;

sleep(60);
return 0;
}

$ test &

$ leaks test

Process 262: 8 nodes malloced for 2 KB
Process 262: 1 leak for 128 total leaked bytes.
Leak: 0x00500120 size=128
0x00000000 0x00000000 0x00000000 0x00000000 ................
0x00000000 0x00000000 0x00000000 0x00000000 ................
0x00000000 0x00000000 0x00000000 0x00000000 ................
0x00000000 0x00000000 0x00000000 0x00000000 ................
0x00000000 0x00000000 0x00000000 0x00000000 ................
0x00000000 0x00000000 0x00000000 0x00000000 ................
0x00000000 0x00000000 0x00000000 0x00000000 ................
0x00000000 0x00000000 0x00000000 0x00000000 ................

I digs me some OS X!

This article was posted by Matty on 2005-12-09 17:09:00 -0400 -0400