我可以't从txt文件中获取值后,删除动态分配的2D数组
I can't delete dynamically allocated 2D array after it gets value from txt file
我创建了一个动态分配的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] )
}
}
然而,主要的问题是,除了第一个
相关文章:
- 使用私有析构函数删除动态分配的对象
- 错误在删除动态分配的2D数组期间发生
- 删除动态分配的数组C
- C 正确删除动态分配的内存
- 必须在C 中删除动态分配的内存
- 删除动态分配的数组时出错
- 循环访问映射并删除动态分配的元素
- 正在删除动态分配的内存
- 何时删除动态分配的内存
- 在C++循环中正确删除动态分配对象的位置
- C++:删除动态分配的类时,是否也会删除不在堆上的私有成员?
- 使用 c_str() 返回的指针删除动态分配的 std::string 是否会导致C++内存泄漏
- 为什么在 C++ 中删除动态分配的数组后不能重用它的名称?
- 从启动动态分配的数组的函数中删除动态分配的数组C++
- 在数组内的对象内删除动态分配的对象
- 删除动态分配内存
- 如何删除动态分配的参数
- c++删除动态分配内存的问题
- 为什么Qt图表示例不删除动态分配的变量
- 我可以't从txt文件中获取值后,删除动态分配的2D数组