xyz
xyz

Reputation: 8927

Why am I getting std::bad_alloc when I have so much free memory available

One of my processes is restarting over and over apparently because of following messages in log file:

Wed Jun 13 10:07:32 2012: terminate called after throwing an instance of 'std::bad_alloc'

Wed Jun 13 10:07:32 2012:   what():  St9bad_alloc

I understand that this is because it is not being able to allocate memory to 'new' request. What I don't understand is that 'free -m' tells me that lot of free memory is available discarding caches:

-bash-3.00$ free -m

         total       used       free     shared    buffers     cached

Mem:         32175      32113         61          0        412      24021

-/+ buffers/cache:       7679      24495

Swap:        12287          0      12287 

Is it cribbing because free memory (with current caching) is very less, but I would guess that to cater to 'new' request, this caching can be released. Or do I need to switch on something to force release of cache or something else is going wrong here?

Upvotes: 0

Views: 4342

Answers (1)

Roee Gavirel
Roee Gavirel

Reputation: 19453

It can be few reasons, a good place to start is with knowing how much memory you are requesting.

I can think of two reason for this to happen which are, an allocation of negative size or a to big size (more than 4GB of 32bit machine). or a fragmentation problem (which can happen after a lot allocation-free calls but it's not that common.)

To see memory fragmentation you can use the magic SysRq key. Simply execute the following command:

echo m > /proc/sysrq-trigger This command will dump current memory information to /var/log/messages. Here is an example of a RHEL3 32-bit system:

Jul 23 20:19:30 localhost kernel: 0*4kB 0*8kB 0*16kB 1*32kB 0*64kB 1*128kB 1*256kB 1*512kB 1*1024kB 0*2048kB 0*4096kB = 1952kB)

==EDIT== how to read the results: when the system is going up it split the memory into 4Mb (4096Kb) chunks of continuous memory. when ever your system allocate memory those chunks are been split up to smaller size and the OS will allocate the closest power of two memory chunk.

So "1*1024kB" mean you have a piece of 1 Mb continuous memory in the system.

In case like: "4*1024kB 0*2048kB 0*4096kB" although you do have 4Mb free, there are split into 4 1Mb chunks. if you would request the OS for 1 allocation of 4 Mb it will fail cause 1 allocation must return a continuous memory.

I hope any of this make sense to you (-;

Upvotes: 5

Related Questions