问题理解堆
Issues understanding heap
本文关键字:问题 更新时间:2023-10-16
我对c++中的堆有一个小小的理解问题。
我创建了一个小类来将Wchar_t-Array转换为Char-Array。这是我的转换类的一部分:
. h
class ConvertDataType
{
private:
char *newChar;
};
. cpp
size_t i;
char *newChar = new char[wcslen(WcharArray)];
wcstombs_s(&i, newChar, strlen(newChar), WcharArray, wcslen(WcharArray));
return newChar;
在Cpp-File中,我动态地在堆中创建了一个新的Char-Array。如何正确删除变量?我读了很多不同的例子……
delete[] newChar;
for循环:
delete[] newChar[i];
我想这样做:
~ConvertDataType(void) //deconstructor
{
delete[] newChar;
}
正确吗?newChar[i]
中的内容会发生什么变化?我只是破坏了指针,不是吗?
好吧,我仍然有问题,内存泄漏发生,如果我使用类?这怎么可能呢?我添加了解构器delete[] newChar;
你做的事情是正确的,通过operator new[]()
分配的内存应该通过operator delete[]()
释放。
但是这里我看到了另一个问题:
wcstombs_s(&i, newChar, strlen(newChar), WcharArray, wcslen(WcharArray));
第三个参数实际上不是您想要的。您想要传递缓冲区的大小,但从newChar
的第一个位置开始传递字符数,直到第一个空字符(请参阅strelen()
的手册了解更多细节)。这里需要wcslen(WcharArray) + 1
(1表示额外的空字符)作为第三个参数,因为它是分配的内存块的实际长度,也应该由new char[wcslen(WcharArray) + 1]
分配。
调用delete[] newChar
才是正确的方法。
char
是一个基本类型,它将不做任何事情。无论如何,在删除数组之后,您不应该访问newChar[i]
。
你的解决方案是正确的。当你调用delete []
时,由指针引用的内存块被设置为空闲,但仅此而已。您的内容将仍然存在,直到您在此地址块中分配另一个内存并覆盖数据。但是不能依赖于从已删除的内存中读取。
使用
size_t new_size = wcslen(WcharArray);
size_t number_of_converted = 0;
this->newChar = new char[new_size];
wcstombs_s(&number_of_converted, this->newChar, new_size, WcharArray, new_size);
本月的char *newChar = new char[wcslen(WcharArray)];
在第二种情况下,创建一个局部变量。在Windows上,我会使用WideCharToMultiByte进行转换:
DWORD mb_size = WideCharToMultiByte(
CP_UTF8, // UTF-8 encoding
0, // flags
WcharArray, // wide char input
-1, // find the end of string
NULL, // no input, we want to know the necessary space
NULL, // no input size
NULL, // no default chars
NULL ); // no used default chars
this->newChar = new char[mb_size];
mb_size = WideCharToMultiByte(
CP_UTF8, // UTF-8 encoding
0, // flags
WcharArray, // wide char input
-1, // find the end of string
this->newChar, // target string
mb_size, // target string size
NULL, // no default chars
NULL ); // no used default chars
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题