Search code examples
c++mingwdynamic-memory-allocation

Simple use of dynamic memory in loop causes bad_alloc


Let's say I have a really simple loop like this:

#include <iostream>

int main() {
    int i = 0;
    while (1)
    {
        char* c = new char[32];

        std::cout << i << " " << c[0] << std::endl;

        delete[] c;
        i++;
    }
    return 0;
}

As you can see at the beginning of the loop I allocate some memory with new operator. I print it out and delete it. If i run this code it works but at one point it stops and throws std::bad_alloc.

I don't understand why that happens. It shouldn't run out of memory since it's freeing it every time with delete. If there was enough memory for the program to go through the loop once or twice it should be enough memory for it to loop indefinitely. And it's just 32 bytes.

I tried to run this on two different computers and each does a different number of loops before it breaks.

Am I doing something wrong?

EDIT: I'm using mingw g++ (gcc) 4.8.1 on Windows 8


Solution

  • I figured out what was wrong. I was using Microsoft Application Verifier for something and I accidentally left the exe selected for testing. And since the low resource simulation test was enabled it simulated the low-memory conditions.

    I didn't realize the verifier works even when it's window is closed. I figured it might be it when I tried to compile the program with different parameters and accidentally changed the output filename. Changing the filename made the program work, so I remembered that I pointed the verifier towards the original exe earlier.

    I feel silly now.