简体   繁体   中英

Constructor of a Struct in C++ Causes Non-Zero Exit Code

When I call the constructor for my SegTree struct in the code below, I keep getting a non-zero exit code. When I comment out the line that initializes the struct, the program runs with no issue. Can someone explain why this is happening and how to fix my code?

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <string>
#include <vector>
#include <string.h>

using namespace std;

struct SegTree{
    int N;
    long long tree [1<<20], arr [1<<20];
    SegTree(int x){ N = x; }
};

int main(){
    SegTree st(len);
    return 0;
}

Please help, and thanks in advance!

EDIT: My issue is not the size of the arrays, as I have mentioned in the comments. I am able to make the arrays and run the code when they are placed outside the struct.

Wow. That's a big structure:

struct SegTree{
    int N;
    long long tree [1<<20], arr [1<<20];

1<<20 is 1 Meg. long long is typically 8 bytes, so your structure is 16 Mbytes ... and you are allocating it on the stack. Typically, programs allocate 1Mbyte for the stack ... so it won't fit!

The solution is to change the arrays into vectors. The array will then be allocated on the heap, and you should be fine:

    std::vector<long long> tree = {1<<20};
    std::vector<long long> arr  = {1<<20};

(once you are using vectors, you may well be able to do much better than allocating the memory all at once at some maximum size in the constructor).

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