【问题标题】:Memory allocation in class类中的内存分配
【发布时间】:2014-06-27 00:52:58
【问题描述】:

我正在尝试编写一个在调用时分配内存并在作用域结束时销毁它的类,就像普通变量一样。

这是我所做的:

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

尝试用它分配一些内存,所以我在每个中都放了一些 printfs。它基本上可以工作,在我分配时调用构造函数,在作用域结束时调用析构函数。在同一范围内使用分配的内存时,一切正常,但是如果我将地址传递给函数(线程)并从那里写入,程序将崩溃(触发断点)

测试了无数次,似乎总是一个随机的地方:

InternetReadFile();
InternetCloseHandle();
ZeroMemory();
and once in _LocaleUpdate class

早期我使用 calloc(),当我不再需要它时,只需释放它。我还有什么需要改变的吗?

这是我分配内存的方式:

GetMem mem(100000);
char *temp = (char *)mem.ptr;

【问题讨论】:

  • 别忘了Rule of Three。复制此类将导致双重删除,这可能是您崩溃的原因(尽管答案指出的错误更有可能)。删除复制构造函数和赋值运算符,以确保它不会被意外复制。

标签: c++ memory-management


【解决方案1】:

改变

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

【讨论】:

  • 非常感谢!这是我的一大失败,不便之处敬请见谅
【解决方案2】:

size 当前在使用点统一化:ptr = calloc(1, size);。这是未定义的行为

更改为ptr = calloc(1, size = lenght);

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 2011-12-02
    • 1970-01-01
    • 2012-03-08
    • 2012-01-12
    • 2013-09-29
    • 2022-01-15
    • 2015-01-18
    • 1970-01-01
    相关资源
    最近更新 更多