c language:
I don't know how to do this
I don't know how to do this
If you put the following in a header file, and include it _after_ all
Standard headers have been included, then you might have some joy. Better
yet, you could find your compiler's <stdlib.h> file and change it.
(Unchecked code, likely to contain a bug or two.)
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct AllocInfo {
void *p;
char const *filename;
unsigned line;
} AllocInfo;
AllocInfo ai_list[512]; /* Allows for 512 separate allocations. */
AllocInfo *ai_current = ai_list;
void CheckFreed(void);
void *const MyMalloc(size_t const len,char const *const file,
unsigned const line)
{
static int first_time = 1;
if (first_time) { atexit(CheckFreed); first_time = 0; }
ai_current->filename = file;
ai_current->line = line;
return ai_current++->p = malloc(len);
}
void MyFree(void *const p)
{
AllocInfo *pai = ai_current;
for(;;--pai) if (p == pai->p) { free(p); pai->p = 0; return; }
}
void ReportLeak(AllocInfo const *const);
void CheckFreed(void)
{
AllocInfo const *pai = ai_list;
for(;;++pai)
{
if (pai->p) ReportLeak(pai);
if (pai == ai_current) return;
}
}
void ReportLeak(AllocInfo const *const pai)
{
printf("Memory leak allocated at:\n %s Line %u\n",
pai->filename, pai->line);
}
#define malloc(len) MyMalloc(len, __FILE__, __LINE__)
#define free(p) MyFree(p)
int main(void)
{
void *const a = malloc(5);
void *const b = malloc(5);
void *const c = malloc(5);
void *const d = malloc(5);
void *const e = malloc(5);
void *const f = malloc(5);
free(b); free(d); free(f);
return 0;
}