我试图编写一个类,在调用时分配内存,并在作用域的末尾销毁它,就像普通变量一样。
以下是我所做的:
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。它基本上起作用,当我分配构造函数时调用构造函数,在作用域结束时调用析构函数。当在相同范围内使用分配的内存时,一切正常工作,但如果我将地址传递给函数(线程)并从那里写入,程序就会崩溃(trigg断点)。
测试了无数次,似乎总是一个随机的地方:
InternetReadFile();
InternetCloseHandle();
ZeroMemory();
and once in _LocaleUpdate class耳塞我使用calloc(),当我不再需要它时,只需释放它。还有什么我需要改变的吗?
下面是我如何分配内存:
GetMem mem(100000);
char *temp = (char *)mem.ptr;发布于 2014-05-09 10:12:39
变化
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);
}
}发布于 2014-05-09 10:16:37
size目前在使用点上是统一的:ptr = calloc(1, size);。这是不明确的行为。
更改为ptr = calloc(1, size = lenght);
https://stackoverflow.com/questions/23561955
复制相似问题