-2

I have N points in trigonometric order that define a polygon. I've used the following code to calculate the area of that polygon but I get a stack overflow and I can't exactly understand why. At first I thought it was the while function getting out of bounds but apparently is not?

#include<iostream>
#include<fstream>
using namespace std;

struct punct {
    long double x;
    long double y;
};

int main()
{
    int N;
    long double aria = 0.0f;
    punct v[100000];
    ifstream f("aria.in");
    ofstream g("aria.out");
    f >> N;
    for (int i = 1; i <= N; i++) {
        f >> v[i].x >> v[i].y;
    }

    int k = 1;
    while (k <= N - 1) {
        aria = aria + (v[k].x * v[k + 1].y - v[k + 1].x * v[k].y);
        k++;
    }

    aria = aria + (v[N].x * v[1].y - v[1].x * v[N].y);
    aria = 1 / 2 * aria;

    g << aria;

    f.close();
    g.close();
    return 0;
}

My input file aria.in has the following:

4
-2 -2
2 -2
2 2
-2 2
Shury
  • 468
  • 3
  • 15
  • 49
  • Which code is the last one still executed? What does the debugger tell you? – JVApen Jan 07 '18 at 08:55
  • 3
    Do not allocate huge arrays such as `punct v[100000];` on the stack because stack space is rather limited. Allocate them on the heap using `::std::vector`. – user7860670 Jan 07 '18 at 09:00
  • 1
    It's likely the fault of `punct v[100000]`. You're allocating **lots** of stack space for this array `16 * 100000 =~ 1.5MB`. Try heap allocation instead. A clue: [use vector](http://en.cppreference.com/w/cpp/container/vector) – tomix86 Jan 07 '18 at 09:01
  • @tomix86 I think long double are (typically) 10 bytes each? Also... reply OP: It's possible to increase stack size by commands (differs for each OS) – user202729 Jan 07 '18 at 09:41
  • @user202729 AFAIK it is architecture and compiler dependent, long double should be *at least* 8 bytes long, see [here](https://stackoverflow.com/questions/3454576/long-double-vs-double). I've done a quick check and with VS2017 compiled for x64 it is indeed 8 bytes. – tomix86 Jan 07 '18 at 09:49

2 Answers2

3

This line

punct v[100000];

Is in error as it is too big for the stack

Use std::vector instead i.e.

#include <vector>

....

std::vector<punct> v(100000);

Also you should check if you have actually opened the files

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

You are trying to malloc 100000 punct on the stack, which leads to a stack overflow.

You can malloc on the heap as:

punct *v = new  punct[100000 + 1];

This should resolve the stack overflow. For completeness, it is good to free the memory after no needed.

delete [] v;

You can also use c++11 new vector

#include <vector>
std::vector<punct> v(100000 + 1);

or array container to do it

#include <array>
std::array<punct, 100000 + 1> v;

Noticed that I add-ed one to 100000, due to that your code looks like 1-starting index based. However, c++ counts index from zero. It is your choice though.

phy nju
  • 289
  • 2
  • 7