Simple use of heap in a loop calls bad_alloc

Let's say I have a very simple loop:

#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 am allocating some memory to the new statement. I will print it and delete it. If I run this code it works, but at some point it stops and throws std :: bad_alloc.

I don't understand why this is happening. It shouldn't run out of memory as it frees it up every time it is deleted. If there was enough memory for the program to cycle through one or two times, it must have enough memory to loop indefinitely. And that's only 32 bytes.

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

Am I doing something wrong?

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

+3


source to share


2 answers


I understood what had happened. I have used Microsoft Application Verifier for something and I accidentally left the exe selected for testing. And since a low resource simulator was run, it simulated low memory conditions.

I didn't know the verifier was working even when closed. I wondered what it might be when I tried to compile the program with different parameters and accidentally changed the name of the output file. Changing the filename made the program work, so I remembered that I had previously pointed the verifier to the original exe.



Now I feel stupid.

+4


source


You are asking if you are doing something wrong.

Technically, your code has undefined behavior (UB) since you are reading c[0]

that has not been initialized.

The other thing is, your code is fine. I suspect odd memory behavior will persist even after you've fixed the UB (please try it!) If this continues, it means the problem has nothing to do with your code and is most likely (rather strange) property your compiler and / or runtime library.



I have tested your code on my computer and I cannot reproduce the behavior:

Apple LLVM version 6.0 (clang-600.0.51) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0

      

+3


source







All Articles