0

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?

Martin B
  • 23,670
  • 6
  • 53
  • 72
SPB
  • 4,040
  • 16
  • 49
  • 62
  • __How much__ memory are you allocating? That is important. – bobobobo Aug 16 '10 at 11:40
  • Is your application 32-bit or 64-bit? (From the "visual-c++" tag, I assume you're running on Windows.) – Martin B Aug 16 '10 at 13:04
  • how did you take the measurement? did you just use the windows task manager and see the memory used? hm.... memory never work that way. – J-16 SDiZ Aug 16 '10 at 13:35
  • ya i am debugging the code on windows vc++.....from there i came to know that malloc was not allocating the memory – SPB Aug 17 '10 at 03:17

2 Answers2

4

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

Community
  • 1
  • 1
Martin B
  • 23,670
  • 6
  • 53
  • 72
0

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
  • 1