Question

I'm trying to write a class that will allocate memory when called and destroy it on end of the scope, just like normal variables.

Here is what I did:

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

Tried allocation some memory with it, so I've put some printfs in each. And it basically work, constructor is called when I allocate, and destructor on end of scope. When using allocated memory in same scope everything is working well, but if I pass address to a function (thread) and write from there program will crash (trigg breakpoint)

Tested numerous times and always seem to be a random place:

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

Earler I used calloc(), and when I don't need it anymore simply free it. Is there anything else I need to change?

Here is how I allocate memory:

GetMem mem(100000);
char *temp = (char *)mem.ptr;
Was it helpful?

Solution

Change

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

to

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

OTHER TIPS

size is currently unitialised at the point of use: ptr = calloc(1, size);. This is undefined behaviour.

Change to ptr = calloc(1, size = lenght);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top