类中的内存分配

Memory allocation in class

本文关键字:分配 内存      更新时间:2023-10-16

我试图写一个类,将分配内存时调用和销毁它的范围结束,就像普通变量。

我是这样做的:

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);