首页 > 解决方案 > 填充另一个二维数组后堆已损坏

问题描述

我正在编写一个程序,我需要获取 2 个文本文件并查看较小图像在较大图像中的位置。为此,我需要使用二维数组。当我只使用一个时,这一切都很好,但是现在我已经用较小图像中的数据填充了第二个数组,我收到一条错误消息:

Wheres Wally.exe 中 0x77338519 (ntdll.dll) 处未处理的异常:0xC0000374:堆已损坏(参数:0x773758A0)。

我已经设法将其缩小到特别是当第二个数组是实际给定值时的一行

//Array Containing Initial Values Of The Base Image
            double* baseImage = new double(largeImageRowSize * largeImageCollumnSize);
            //Array Containing Values Of The Small Image
            double* wallyImage = new double(smallImageRowSize * smallImageCollumnSize);

            //Fill BaseImage with all values from the text file
            baseImage = read_text("Cluttered_scene.txt", 1024, 768);

            //Allocate 36 arrays for each row (so 49x36 arrays)
            for (int i = 0; i < getLargeRowSize(); i++)
                a2dArray[i] = new double[getLargeCollumnSize()];

            //Put data of image into 2d array
            int largeImageCounter = 0;
            for (int y = 0; y < getLargeCollumnSize(); y++) {
                for (int x = 0; x < getLargeRowSize(); x++) {

                    a2dArray[y][x] = baseImage[largeImageCounter];
                    largeImageCounter++;
                    //cout << a2dArray[x][y];
                }
            }

            //Fill wallyImage array with all values of the small wally text file
            wallyImage = read_text("Wally_grey.txt", 49, 36);

            //Allocate 36 arrays for each row (so 49x36 arrays)
            for (int i = 0; i < getSmallRowSize(); i++)
                a2dArrayForWally[i] = new double[getSmallCollumnSize()];

            //Put data of image into 2d array
            int smallImageCounter = 0;
            for (int y = 0; y < getSmallCollumnSize(); y++) {
                for (int x = 0; x < getSmallRowSize(); x++) {

                    a2dArrayForWally[y][x] = wallyImage[smallImageCounter];
                    smallImageCounter++;
                    //cout << a2dArray[x][y];
                }
            }

给出错误的行在最后的 for 循环中

a2dArrayForWally[y][x] = wallyImage[smallImageCounter];

所以显然这与存储内存的位置有关,但我是 C++ 新手,在谷歌搜索后,我似乎找不到我的代码有什么问题。

任何帮助将不胜感激!

编辑:

通过自己尝试解决错误,我发现当smallImageCounter达到 430 时出现问题。在此之前存储数据没有问题

标签: c++

解决方案


new double()new double[]. 第一个分配一个单一 double的并将其初始化为括号中的值,其中第二个分配double一个大小为方括号的 s 的动态数组。

改变:

double* baseImage = new double(largeImageRowSize * largeImageCollumnSize);
double* wallyImage = new double(smallImageRowSize * smallImageCollumnSize);

至:

double* baseImage = new double[largeImageRowSize * largeImageCollumnSize];
double* wallyImage = new double[smallImageRowSize * smallImageCollumnSize];

推荐阅读