我可以't从txt文件中获取值后,删除动态分配的2D数组

I can't delete dynamically allocated 2D array after it gets value from txt file

本文关键字:删除 动态分配 数组 2D 获取 文件 txt 我可以      更新时间:2023-10-16

我创建了一个动态分配的2D数组,并使用它来存储txt文件中的灰度值。我确信它得到了正确的值,但出现了一条错误消息,上面写着"检测到堆损坏,CRT检测到应用程序在堆缓冲区结束后写入内存"。

但如果我删除了"//********"部分的代码,则不会出现任何警告。请帮我一下,谢谢。

#include "stdafx.h"
typedef unsigned char byte;
int _tmain(int argc, _TCHAR* argv[])
{
    const char *sLoadPath = "D:\Matlab Work\pout.txt";
    FILE *file_handle;
    const int iImgH = 291, iImgW = 240;
    byte **ppu8Image = new byte *[iImgH];
    ppu8Image[0] = new byte [iImgH*iImgW];
    for (int i = 1; i < iImgH; i++)
    {
        ppu8Image[i] = ppu8Image[i - 1] + iImgW;
    }
    //******************************
    file_handle = fopen(sLoadPath, "r");
    for (int i = 0; i < iImgH*iImgW; i++)
    {
        fscanf(file_handle, "%d", &ppu8Image[i / iImgW][i % iImgW]);
    }
    fclose(file_handle);
    //******************************
    delete[] * ppu8Image;
    delete[] ppu8Image;
    ppu8Image = NULL;
    system("pause");
    return 0;
}

与其他答案中所说的相反,您的内存分配是正确执行的。

不过,一个明显的错误是,您正在使用fscanf中的%d格式说明符读取数据。格式%d需要类型为int *的参数,并将数据保存到内存中的int对象中。但是您为fscanf提供了一个类型为byte *的参数,即unsigned char *unsigned char小于int,这意味着fscanf覆盖(销毁)一些您不拥有的内存。这种损坏正是后来检测到的堆损坏。

若要从文件中fscanf个单独的unsigned char值,请使用%c格式说明符。但是,在不知道文件格式的情况下,无法说明如何正确读取文件。

给定所需的过程是分配一个指向字节的指针数组

然后为每行分配字节

然后这个代码块:

for (int i = 0; i < iImgH*iImgW; i++)
{
    fscanf(file_handle, "%d", &ppu8Image[i / iImgW][i % iImgW]);
}

实际上应该是一对嵌套的"for"循环,类似于:

for( int i = 0; i < iImgH; i++ )
{
    for( int j = 0; j < iImgW; j++)
    {
         fscanf...  ppu8Image[i][j] )
    }
}

然而,主要的问题是,除了第一个

之外,没有为指向字节的指针数组分配任何指针