【问题标题】:C++ Stack Overflow initialising arrayC++ 堆栈溢出初始化数组
【发布时间】:2023-04-09 08:26:01
【问题描述】:

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

我已经创建了“TreeEdge.h”和“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;
}

但是,我收到一个错误:“MST.exe 中 0x00007FF6E91493D8 处未处理的异常:0xC00000FD:堆栈溢出(参数:0x0000000000000001、0x0000002BFF003000)。”随着程序进入主函数。

感谢您的帮助。

罗伯

【问题讨论】:

标签: c++ exception stack overflow


【解决方案1】:

您使用数组在堆栈上分配了太多内存。

 sizeof(TreeNode); // Returns 88 bytes

因此,在分配 544x1024 元素的二维数组时,您试图在堆栈上分配 ~49MB!根据Windows Thread Documentation,进程的默认堆栈大小为 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
}

【讨论】:

  • 感谢您的帮助,我已经开始使用向量,并且得到了相同的结果,而且错误更少!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-22
  • 2012-12-20
  • 2011-03-02
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多