Después de algún tiempo de trabajar con C, decidí desarrollar una librería muy fácil de usar que pudiera ayudar a detectar y trazar fugas de memoria (memory leaks).
Hay muchas soluciones para esto en la red, pero esta tiene la particularidad de ser realmente simple de implementar.
Simplemente hay que agregar el siguiente include al archivo principal de inclusión (un archivo que sea incluido por cada archivo del proyecto) o, en el caso de que no haya uno, a cada archivo que llame a una función de alocación de memoria (malloc, realloc, calloc o free). La única precaución extra que hay que tener en cuenta es incluirlo después de los headers standard (stdio.h, stdlib.h, malloc.h, etc.).
Esta es la línea:
#include "cMemDbg.h"
Eso es todo… Esperabas más? Bueno, hay un último paso… Tenés que hacer esta llamada justo antes de salir del programa para poder obtener las conclusiones detalladas:
PrintMemoryLeakInfo();
Fácil, no?
Eso fue todo… En serio.
Ahora, antes de ir a funcionalidades más “de experto”, voy a dejar el link para descargar la librería para aquellos que no quieran seguir leyendo:
Ahora continuemos…
Esta librería viene con tres parámetros configurables (disponibles en cMemDbg.c):
- PRINT_OPERATIONS: Si está seteado en 1, se va a imprimir a la salida configurada (stdout por default) cada operación de alocación de memoria realizada en el programa (alocación o liberación). De otro modo, la librería sólo imprimirá problemas, notificaciones y el dump final. [Valor predeterminado = 1]
- MAX_ALLOC: Largo del stack interno de memoria de la librería (en elementos). Es la máxima cantidad de alocaciones que pueden ser trazadas sin ser liberadas. Se puede incementar este valor a voluntad en casi de ser necesario. De hecho, si es necesario, la librería imprimirá un mensaje diciendo: “INTERNAL_ERROR: Allocation stack overflow, please increase MAX_ALLOC”. [Valor predeterminado = 256]
- PRINT_OUTPUT: Destino de impresión de las notificaciones generadas por la librería (puede ser cualquier stream/archivo en el que se pueda imprimir utilizando fprintf). [Valor predeterminado = stdout]
Finalmente, hay dos funciones más que se pueden utilizar en caso de ser necesario:
- PrintTotalAllocatedMemory(): Imprime la cantidad acumulativa de memoria alocada al momento de la llamada.
- PrintMemoryReservedByCMemDbgLibrary(): Imprime la cantidad de memoria reservada por la librería (definida en tiempo de compilación por la constante MAX_ALLOC).
Eso es todo… Dije que era fácil de usar.
De todos modos si, luego de leer los comentarios del archivo cMemDbg.h, tenés algún tipo de pregunta, comentario o sugerencia, no dudes en contactarme.
Support appreciated!
All the content offered in this website is, except noted otherwise, of free nature. This means you can share it wherever you want if you do it freely and stating its source.
If it was useful for you and you’d like to contribute, you can make a donation or, at least, visit one of our advertisers of your choice; they are all around the site.
The article is ver good. Write please more
Thank you Kelly!
I’ll soon release the cppMemDbg library (similar to this one, but prepared to work with C++ (new, new [], delete & delete []))…
CYA!
Hi. I’m testing your library and it seems to be working very well.
I program in C for my company’s FreeBSD servers and would like to suggest a patch for your library to support FreeBSD systems due to libc differences.
Nice work!
Regards,
Sérgio
File: freebsd.patch
— cMemDbg.c 2009-11-09 19:56:45.000000000 -0200
+++ cMemDbg.c.dist 2009-04-08 15:45:22.000000000 -0300
@@ -33,10 +33,7 @@
#include
#include
-// FreeBSD has malloc inside stdlib
-#ifndef __FreeBSD__
#include
-#endif /*__FreeBSD__*/
//Configuration Constants ***************
#define PRINT_OPERATIONS 1
The comment system stripped the includes. LOL. If you want me to send the patch to you by mail, just let-me known.
Regards,
Sérgio
Thank you Sérgio for your comment!
I’m very happy this library was useful for you…
Please send me the diff via the Contact section so your code doesn’t get stripped
I’ll include your header changes in the following release…
BTW, if you work with C++ code, you can use the cppMemDbg version…
Thanks again!
NeoEGM.
It’s a very interesting library but, what should I modify to get a memory leak log file like, for example, “leaks_log.txt”? I have tried to replace the line:
#define PRINT_OUTPUT stdout
by a (FILE*) but the compiler does not accept it.
Hi! Thanks for your comment!
stdout is not a FILE* but a file descriptor integer (the ones returned by the “open” function). So you should replace it with other of the same kind.
You can get a file descriptor from a FILE* using the function “int fileno(FILE *stream)”.
Given a global FILE* f, you could replace the line this way and it should work:
#define PRINT_OUTPUT (fileno(f))
Best regards!
NeoEGM.