Mail Archives: djgpp/1998/09/01/23:32:17
sl AT psycode DOT com DOT REMOVE_THIS wrote:
>
> On Tue, 1 Sep 1998 01:14:05, fesenko AT pacific DOT net DOT sg (Victor) wrote:
>
> > On Mon, 31 Aug 1998 12:16:52 +0300 (IDT), Eli Zaretskii
> > <eliz AT is DOT elta DOT co DOT il> wrote:
> > But is there a way to find the amount of used memory then? That was
> > actually a real purpose of checking remaining memory. I was looking
> > that the remaining memory didn't go too low. If it did it meant I had
> > memory leaks somewhere.
>
> Same here .. There is no way to check for memory leaks .. :(
Not true. A very simple way follows, though not tested:
---- file leakchk.c ---
#include <stdlib.h>
#include <sys/types.h>
#define NO_WRAP
#include "leakchk.h"
static size_t total_alloc = 0;
void *malloc_wrap(size_t s)
{
size_t *t;
if ((t = (size_t *)malloc(s + sizeof(size_t))) != NULL)
{
total_alloc += s;
*t = s;
return (void *)(t + 1);
}
else return NULL;
}
void *realloc_wrap(void *p, size_t ns)
{
/* Lazy implementation */
free_wrap(p);
return malloc_wrap(ns);
}
void free_wrap(void *p)
{
size_t s;
size_t *rp;
rp = (size_t *)p;
s = *(--rp);
assert(s <= total_alloc);
s -= total_alloc;
free(p);
}
static void report_leak(void) __attribute__((destructor));
static void report_leak(void)
{
if (total_alloc > 0)
fprintf(stderr, "Leaked %d bytes\n", total_alloc);
}
------ end -----
------ file leakchk.h ---
#include <sys/types.h>
void *malloc_wrap(size_t);
void *realloc_wrap(void *, size_t);
void free_wrap(void *);
#ifndef NO_WRAP
#define malloc malloc_wrap
#define realloc realloc_wrap
#define free free_wrap
#endif
------- end -------
And just add #include "leakchk.h" in each file of your program.
Systems such as MSS give better diagnostics. Yes, it can be done.
--
Nate Eldredge
nate AT cartsys DOT com
- Raw text -