2

I'm using gcc4.4.4 and gdb on 64bit Linux centos 5.7, compiling to ansi C. I'm not sure why my code tests true for PDF == NULL below, and calls exit(2).

void func(...)
...
double *PDF;
...
PDF = malloc( sizeof(double) * 1 );
if (PDF == NULL) {
    exit(2); 
}

Using free -m, I observe before the program starts:

             total       used       free     shared    buffers     cached
Mem:          2001       1955         46          0         71        975
-/+ buffers/cache:        907       1094
Swap:         4008        688       3319

and when the program sits on the exit(2); line of code, free -m reads:

             total       used       free     shared    buffers     cached
Mem:          2001       1970         31          0         72        976
-/+ buffers/cache:        921       1080
Swap:         4008        688       3319

In both cases, there's plenty of memory available in the cache row, free column (certainly enough for one byte).

What are other possible reasons PDF would become NULL? What coding bugs could cause this?

In case it matters, I've been using gdb a lot in the last week, exiting the program using "q" then "y" instead of letting it complete (figuring all malloc memory would be freed by the program terminating thus not needing to execute the free() code).

1
  • Can we see a SSCCE sample (main(), includes, and gcc flags) that reproduces the issue? Commented Dec 7, 2011 at 17:30

2 Answers 2

4

If you've written beyond the bounds of a buffer somewhere, you may have corrupted the heap, in which case all bets are off.

I suggest using e.g. Valgrind to check that you haven't done something like this.

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

6 Comments

Doesn't even work for allocating one byte (updated question above).
@ggkmath: Doesn't matter; if the heap is corrupted then the heap is corrupted.
Indeed, all the more reason to believe the heap is corrupted.
I am doing a lot with the heap before this point, so this is possibly the cause. Is there any good way to debug this using gdb?
@ggkmath: It would be far easier to use a proper memory debugger, such as Valgrind. It's designed to diagnose exactly this sort of problem.
|
0

malloc returns NULL when the calling process cannot allocate anymore memory, perhaps because a mmap system call fails because you reached some limits, like those set by setrlimit

An individual process can reach its limit even if some memory is available to other processes.

You can use strace to trace the system calls and find out which one is failing.

And be sure to compile with gcc -Wall -g (and use the debugger gdb).

Comments

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.