tags:

views:

78

answers:

2

I am allocating memory using malloc and freeing it after using it, but in every third operation I notice that malloc is not allocating the memory.

Can anyone tell me what is happening... why malloc is not working... what should I do to allocate memory?

Posting code is difficult as it involves lots and lots of files.. mostly I think that it's running out of memory... so maybe I can determine somehow how much memory I am wasting or using?

A: 

why do you think "malloc is not allocating the memory" ? Is it returning NULL, or are you looking at some system memory stats. If it's the latter it could be because your C library implementation is holding onto previously allocated memory, rather than returning it directly to the system.

John
MALLOC is returning NULL
SPB
@SPB: That means malloc ran out of memory.
MSalters
+2  A: 

As others have remarked, malloc() is returning NULL because your application has run out of memory (or, more precisely, virtual address space).

If I understand your description correctly, you're successfully running the same workload twice, but the third time you try, you're out of memory.

There are basically two things that could be happening here:

  1. You're leaking memory. (I see you say that you're freeing the memory you use, but leaking memory accidentally is awfully easy to do.) You can find information on Visual C++'s built-in features for leak detection here.

  2. You're fragmenting memory. As applications have started using a significant portion of the available 32-bit address space, fragmentation has started to become a real problem. Unfortunately, there isn't really a cut-and-dried solution to this problem, but take a look at these SO questions for more information:

    How to avoid heap fragmentation?

    How to solve Memory Fragmentation

    Memory management in memory intensive application

Martin B
This is a good answer to this otherwise very ambiguous question
bobobobo