C ++ Stack Overflow初始化数组

时间:2017-11-09 11:29:34

标签: c++ exception stack overflow

我在初始化我创建的类型的数组时遇到了一些问题。

我创建了#34; TreeEdge.h"和#34; TreeNode.h",可以在以下代码中看到:

#pragma once
#include "TreeEdge.h"

class TreeNode {

TreeEdge northEdge;
TreeEdge eastEdge;
TreeEdge southEdge;
TreeEdge westEdge;
int xCoord;
int yCoord;

public:

// Default constructor
TreeNode() {

}

//constructor 2
TreeNode(int xInput, int yInput) {
    xCoord = xInput;
    yCoord = yInput;
}

void setEastSouthEdges(TreeEdge east, TreeEdge south) {
    eastEdge = east;
    southEdge = south;
}

void setAllTreeEdges(TreeEdge north, TreeEdge east, TreeEdge south, TreeEdge west) {
    northEdge = north;
    eastEdge = east;
    southEdge = south;
    westEdge = west;
}
};

#pragma once


class TreeEdge {

float weight;
int coords[4];

public:

TreeEdge() {

}

TreeEdge(int firstXCoord, int firstYCoord) {
    coords[0] = firstXCoord;
    coords[1] = firstYCoord;
}

void setWeight(float inputWeight) {
    weight = inputWeight;
}

float getWeight() {
    return weight;
}

void setStartCoords(int xCoord, int yCoord) {
    coords[0] = xCoord;
    coords[1] = yCoord;
}

int * getCoords() {
    return coords;
}

void setEndCoords(int xCoord, int yCoord) {
    coords[2] = xCoord;
    coords[3] = yCoord;
}
};

然后我尝试简单地初始化一个TreeNode数组,希望用它做一些有用的事情,使用下面的代码......

#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <stdio.h>

#include "TreeEdge.h" 
#include "TreeNode.h"

using namespace cv;
using namespace std;

int main()
{
// create 2D array for tree
TreeNode imageTreeNodes[544][1024]; // ???????????????? way to use none fixed values

waitKey(0);
return 0;
}

但是,我收到错误:&#34; MST.exe中0x00007FF6E91493D8处的未处理异常:0xC00000FD:堆栈溢出(参数:0x0000000000000001,0x0000002BFF003000)。 &#34;一旦程序进入主函数。

感谢您的帮助。

罗布

1 个答案:

答案 0 :(得分:1)

您正在使用阵列在堆栈上分配太多内存。

 sizeof(TreeNode); // Returns 88 bytes

因此,在分配544x1024元素的二维数组时,您试图在堆栈上分配~49MB!根据{{​​3}},进程的默认堆栈大小为1Mb,因此您遇到的堆栈溢出异常是因为进程内存不足。

虽然可以增加进程堆栈大小,但最好还是在堆上分配数组。这可以使用原始newdelete来完成,但也许更好的选择是使用std::vector。所以改变你的main()看起来像:

int main()
{
  std::vector<std::vector<TreeNode>> array(544, std::vector<TreeNode>(1024,TreeNode())) ;
  std::cout << "Array number of rows: " << array.size() << std::endl; // Prints 544
  std::cout << "Array number of columns: " << array[0].size() << std::endl; // Prints 1022
}