删除字节转换的char*
Delete char* for byte conversion
我每次读取文件时都尝试使用不同的长度字节读取二进制文件。获得该值后,我尝试将字节转换为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;`
相关文章:
- 将无符号char*转换为std::istream*C++
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将函数参数"const char*"转换为"std::string_view"是
- C ++如何在使用"tolower"时将char转换为int
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- 如何在虚幻引擎4中将char*转换为TCHAR?
- C++:将模板类型 char 转换为 std::string
- strcmp/char* 转换无法按预期工作
- C++中的SQLite char*转换
- 无法从 const char* 转换为 const char *&
- 在 C++ 中将 char 转换为 int,而无需符号位传播
- 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- 试图使用strCMP时的char转换错误
- 无法从'const char *'转换为'LPCTSTR'
- 将 std::vector<char> 转换为字符* 会导致字符缺陷
- 使用 static_cast 将 char 转换为 int c++
- 如何在 C++(MFC) 中将 char* 转换为 LPCTSTR
- 无法将const char转换为字符串构造字符串