GetTotalMemory distribution in C

I would like to get the shared memory allocated before and after the function call to determine if I freed everything correctly or not.

I do this in C and I'm very rusty, so forgive me if this is a naive question. I am looking for something similar to C # GC.GetTotalMemory (true), and it is now on Windows.

Currently, I use PROCESS_MEMORY_COUNTERS_EXboth GetProcessMemoryInfo(...)before and after the function call, but I can not make headers or tails of the output, because if I go into the function and comment out the call, free(...)it will give me the same results (after there will always be more). Here is what I have right now ...

GetProcessMemoryInfo(hProc, &before, sizeof(before));
r = c->function();
GetProcessMemoryInfo(hProc, &after, sizeof(after));

if(r->result != 0) {
    printf("error: %s\r\n", c->name);
    printf("  %s\r\n", r->message);
    printf("  %s (%d)\r\n", r->file, r->line);
    failed++;
}
else if(after.PrivateUsage > before.PrivateUsage) {
    printf("memory leak: %s\r\n", c->name);
    printf("  %d kb\r\n", after.PrivateUsage - before.PrivateUsage);
    failed++;
}
else succeeded++;

Result:

after.PrivateUsage - before.PrivateUsage = 12288

If I go and comment on some calls for free, I get the same result. How can I determine the current total memory size that I allocated using malloc?

+3
3

- c , . AFAIK, . - , , .

, malloc c. .
- malloc, , , :

void* my_malloc(size_t size, const char *file, int line, const char *func)
{

    void *p = malloc(size);
    printf ("Allocated = %s, %i, %s, %p[%li]\n", file, line, func, p, size);

    /*Link List functionality goes in here*/

    return p;
}

#define malloc(X) my_malloc( X, __FILE__, __LINE__, __FUNCTION__)

, , . : , , ..
free(), . , , , .
, , , . api , , .

, .. .

+5

- ( Stack Overflow!), malloc free, malloc free.

- , :

// in some common header file, let say mem_metrics.h
#define malloc malloc_with_metrics
#define free   free_with_metrics

extern size_t num_current_allocs;
void* malloc_with_metrics(size_t size);
void free_with_metrics(void* ptr);


// in mem_metrics.c
#undef malloc
#undef free

size_t num_current_allocs = 0;

void* malloc_with_metrics(size_t size)
{
    ++num_current_allocs;
    return malloc(size);
}

void free_with_metrics(void* ptr)
{
    --num_current_allocs;
    free(ptr);
}

, , num_current_allocs. , , ! , num_current_allocs 0 .

: - , , , , malloc_with_metrics , free_with_metrics.

, .., ; , , - .

+3

You can use Valgrind to check if you freed up all the dynamically allocated memory when exiting the process.

0
source

All Articles