删除字节转换的char*

Delete char* for byte conversion

本文关键字:char 转换 字节 删除      更新时间:2023-10-16

我每次读取文件时都尝试使用不同的长度字节读取二进制文件。获得该值后,我尝试将字节转换为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;,它会导致内存泄漏吗?有任何提高我的代码的建议吗?

this:

b = new char(sizeof(s));

应该是:

b = new char[sizeof(s)];

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

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

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

虽然大卫·萨克森(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;`