4

每次读取文件时,我都尝试使用不同长度的字节读取二进制文件。得到值后,我尝试将字节转换为char*.

我创建了一个简单的代码如下:

//This code is compiled in Visual Studio 2010
typedef unsigned char BYTE;

BYTE *s;
s = new BYTE[3]; // I read 2 bytes from the file, I add +1 to reserve NULL
s[0]= 'a'; s[1]='b';s[2]=NULL;  //just an example I get 2 bytes from file

char* b;
b = new char(sizeof(s));
strcpy(b,(char*)s);
s[0]='x';
cout << s <<"--"<< b<< "--"<< endl;
delete[] s;
delete[]  b;
cin.get();
return 0;`

但是,代码会生成错误“检测到堆损坏”。当我删除该行时,delete[] b;程序运行良好。但我不确定下次是否会出现问题。请有人解释一下吗?如果我删除它会导致内存泄漏delete[] b;吗?有什么建议可以改进我的代码吗?

4

2 回答 2

7

这:

b = new char(sizeof(s));

应该:

b = new char[sizeof(s)];

否则,您不会创建一个数组,而只是创建一个指向具有 sizeof(a) 字符代码的 char 的指针。

因此 delete[] b 导致它崩溃,因为您试图删除没有数组的数组。

还有一个问题,sizeof(s) 不会给你你想要的。s 是一个动态分配的数组,因此调用 sizeof(s)不会为您提供 s 中字符大小的总和。sizeof(s) 将返回指向 s 的指针的大小。

于 2012-12-20T03:03:10.193 回答
3

虽然 David Saxon 已经解释了您的错误的直接原因,但您的代码可以通过使用 C++ 标准库得到显着改进:

//This code is compiled in Visual Studio 2010
typedef unsigned char BYTE;

//s will be automatically destroyed when control leaves its scope
//so there is no need for the `delete[]` later on, and there
//will be no memory leaks if the construction of `b` fails.
std::vector<BYTE> s(3);// I read 2 bytes from the file, I add +1 to reserve NULL
s[0]= 'a'; s[1]='b';s[2]=NULL;  //just an example I get 2 bytes from file
//`sizeof s` is wrong, as it gives the size of the `s` object, rather than
//the size of the allocated array.
//Here I instead just make `b` as a copy of `s`.
std::vector<BYTE> b(s);
s[0]='x';
cout << s.data() <<"--"<< b.data() << "--"<< endl;
//There is no need for `delete[] s` and `delete[] b` as `s` and `b`
//have automatic storage duration and so will automatically be destroyed.
cin.get();
return 0;`
于 2012-12-20T03:19:19.677 回答