Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char pointer is struct array memory leak

I'm having memory leaks in a larger program and I believe this is the cause of it.

#include <stdlib.h>
#include <Windows.h>

typedef struct _struct{
    char* name;
} str;

int main() {
    system("PAUSE");

    str* Character = (str*)malloc(sizeof(str) * 20000);

    for(int i = 0; i < 20000; i++){
        Character[i].name = (char*)malloc(20000);   // Assign memory.
    }

    for(int i = 0; i < 20000; i++){
        free(Character[i].name);            // Free memory.
    }

    free(Character);
    system("PAUSE");
}

Memory at first pause: ~500K.

Memory at second pause: ~1.7M.

Using VS2012 for testing. Any ideas?

like image 441
Marc Avatar asked Jun 10 '13 10:06

Marc


People also ask

What is memory leak in pointers?

A memory leak is a dynamically allocated block of memory that has no pointers pointing to it anywhere in the data space of the program. Such blocks are orphaned memory. Because there are no pointers pointing to the blocks, programs cannot even reference them, much less free them.

Does malloc cause memory leak?

At the malloc() , new memory is allocated, but it is never assigned to a pointer. There is no way to keep track of the memory and no way to deallocate it; thus, we have a memory leak.

Does function create memory leak?

No it does not cause memory leaks.

Can you have a memory leak in the stack?

If the compiler has a bug, you could have a stack memory leak. For some obscure reason it "forgets" to call the destructor of a local variable.


2 Answers

How are you measuring the amount of memory occupied by the program? One thing off the top of my head is that you're looking at the size of the working set the OS is keeping track of. Since you've allocated and freed a lot of memory, the size of that set has increased. Some OSs will adjust the size of the working set after a while, some won't. What OS are we looking at here?

like image 179
idoby Avatar answered Oct 11 '22 15:10

idoby


When you call malloc, memory is allocated on the heap. If there is insufficient space left on the heap, the program will ask the OS for more memory and another chunk is acquired. Memory acquired from the OS is usually not returned until the program finishes (although this is up to the OS).

Program size alone can not normally be used to check for memory leaks! Use Valgrind or a similar tool to check for memory that never gets freed.

like image 43
Klas Lindbäck Avatar answered Oct 11 '22 15:10

Klas Lindbäck