0

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;
Zong
  • 6,160
  • 5
  • 32
  • 46
user3213103
  • 133
  • 3
  • 14
  • 2
    Don't forget the [Rule of Three](http://stackoverflow.com/questions/4172722). Copying this class will result in a double-deletion, which might be the cause of your crash (although the bug pointed out by the answers is more likely). Delete the copy constructor and assignment operator, to make sure it's never accidentally copied. – Mike Seymour May 09 '14 at 10:16

2 Answers2

3

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);
    }
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
3

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

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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483