stack overflow error in C++ program

后端 未结 2 1574
小蘑菇
小蘑菇 2020-12-07 03:27

So i have this complex class , and i want to have an 2d array of complex numbers this is part of the code not all the code

class Complex {
public:
    /* con         


        
2条回答
  •  暖寄归人
    2020-12-07 04:09

    Any idea why?

    Some compilers default the stack size to 1MB. You are allocating 65536 Complex objects that occupies 2 * sizeof(double) memory each. Assuming double to be 8 bytes (this information is implementation defined) you are effectively trying to allocate 16 * 65536 bytes (without considering possible paddings), which are 1048576 bytes, that causes the overflow.

    An alternative is using dynamic allocation with a wrapper, that simulates a bi-dimensional array indexing, along the lines of this one:

    template
    class G {
    private:
        std::unique_ptr mem;
    public:
        G() : mem(new Complex[A * B]) {}
        Complex& operator()(std::size_t a, std::size_t b) {
            return mem[a * B + b];
        }
        Complex  operator()(std::size_t a, std::size_t b) const {
            return mem[a * B + b];
        }
    };
    

    Then you program simply becomes:

    int main(int, char*[]) {
        G<256, 256> g;
        g(0, 0) = ...;
    }
    

    Of course you can generalize your wrapper G for a generic type with templates, but that's outside the scope of this answer.


    On a side note, you destructor:

    ~Complex() { r=0.0; i=0.0; }
    

    is useless. Don't re-initialize memory that will be destroyed anyway when it leaves the scope.

提交回复
热议问题