简体   繁体   中英

C++ loop memory error?

I have some code here where there is an array of "Bacon" objects. I can compile and run it and add objects to the array, but when I make the array size more than one million, I run it and it says 'bacon.exe has stopped working' and I have to close it. I think it might be a memory leak, but I am still learning about that. I am using netbeans ide, and I tried allocating more memory when it gets compiled, but I couldn't figure out how to do that. Note: It isn't because my whole computer runs out of memory, because I still have 2GB free after running the program. Here is my code:

#include <iostream>
#include "Bacon.h"
using namespace std;

int main() {
    const int objs = 1000000;
    Bacon *bacs[objs];
    for(int i = 0;i < objs;i++){
        bacs[i] = new Bacon(2,3);
    }
        for(int i = 0;i < objs;i++){
        bacs[i]->print();
    }
    cin.ignore();
    return 0;
}

Your computer has plenty of memory, but only so much of it can be allocated on the stack. Try allocating it on the heap instead:

Bacon **bacs = new Bacon*[objs];

and later:

delete[] bacs;

You're probably out of stack space.

You allocate huge array of pointers right on stack. Stack is limited resource (usually 8 megabytes per process). Size of pointer is usually 4 or 8 bytes; multiply it by one million and you overrun that limit.

As I learned, when you request for space from memory, if the operation system, which you use(Windows in this case, I think), lets you to take it, you can take and use that space.

For some reason, Windows may not be letting you to take that memory for this situation. But I'm not that much expert in this field. I am stating this as a thought.

The default stack size (windows visual studio 2005, probably others keep the same number) is 1MB, check out http://msdn.microsoft.com/en-us/library/tdkhxaks%28v=vs.80%29.aspx to change it

ulimit in linux to change it.

The heap solution is valid too, but in your example you don't need heap. Requesting heap memory to the OS for something that won't escape the current function is not a good practice. In assembler the stack is translated just to a bigger subtraction, heap is requested thru other methods that require more processing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM