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?

4
  • How much memory are you allocating? That is important. Commented Aug 16, 2010 at 11:40
  • Is your application 32-bit or 64-bit? (From the "visual-c++" tag, I assume you're running on Windows.) Commented Aug 16, 2010 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. Commented Aug 16, 2010 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 Commented Aug 17, 2010 at 3:17

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is a good answer to this otherwise very ambiguous question
Is there a way when malloc would not return at all and crashes ?
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.

1 Comment

@SPB: That means malloc ran out of memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.