删除char *进行字节转换

时间:2012-12-20 02:57:21

标签: c++ c

每次读取文件时,我都尝试使用不同的长度字节读取二进制文件。获得值后,我尝试将字节转换为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;`

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

2 个答案:

答案 0 :(得分:7)

此:

b = new char(sizeof(s));

应该是:

b = new char[sizeof(s)];

否则你不是在创建数组,只是创建一个指向字符代码为sizeof(a)的char的指针。

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

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

答案 1 :(得分: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;`
相关问题