类中的内存分配
Memory allocation in class
我试图写一个类,将分配内存时调用和销毁它的范围结束,就像普通变量。
我是这样做的:
class GetMem {
public:
GetMem(UINT);
~GetMem();
void *ptr;
UINT size;
};
GetMem::GetMem(UINT lenght) {
ptr = calloc(1, size);
if (!ptr){
MessageBox(hwnd, "cant alloc", "error", MB_OK);
exit(0);
}
size = lenght;
}
GetMem::~GetMem() {
free(ptr);
size = 0;
}
尝试为它分配一些内存,所以我在每个中都放了一些打印。它基本工作了,分配时调用构造函数,在作用域结束时调用析构函数。当在相同范围内使用分配的内存时,一切都工作得很好,但如果我将地址传递给函数(线程)并从那里写入,程序将崩溃(触发断点)
测试了很多次,似乎总是一个随机的地方:
InternetReadFile();
InternetCloseHandle();
ZeroMemory();
and once in _LocaleUpdate class
前面我使用了calloc(),当我不再需要它时,只需释放它。还有什么需要更改的吗?
下面是我分配内存的方法:GetMem mem(100000);
char *temp = (char *)mem.ptr;
变化
GetMem::GetMem(UINT lenght) {
// up to now, value of size is indeterminate
ptr = calloc(1, size); // undefined behavior using indeterminate value
if (!ptr){
MessageBox(hwnd, "cant alloc", "error", MB_OK);
exit(0);
}
size = lenght;
}
GetMem::GetMem(UINT lenght) {
size = lenght; // <- set size first before using it
ptr = calloc(1, size);
if (!ptr){
MessageBox(hwnd, "cant alloc", "error", MB_OK);
exit(0);
}
}
size
目前在使用点是一元化的:ptr = calloc(1, size);
。这是未定义行为。
改成ptr = calloc(1, size = lenght);
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 如果 const 不分配内存,为什么我可以获取 const 的地址?
- 在函数中分配内存时出现问题
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- constexpr new 如何分配内存?
- 在构造函数中分配内存失败是如何冒泡的
- LLVM 传递以在特定地址分配内存
- CudaMalloc 在分配内存时失败
- 为什么它在不分配内存的情况下工作正常
- 为什么在正确解除分配内存时出现内存泄漏?
- 如何通过 malloc 为队列数组分配内存?
- vector是否为std::移动的对象连续分配内存
- 删除类成员的动态分配内存的最佳方法是什么
- 唯一指针是否在堆或堆栈上分配内存?
- 如果不分配内存,我如何能够为变量创建和分配值?
- std::initializer_list 堆是否分配内存?
- 如何按顺序或在指定的地址分配内存?
- 是否可以使用 malloc 为类对象分配内存?
- 迭代器是否分配内存(如指针)?