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; 
1
  • 2
    Don't forget the Rule of Three. 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. Commented May 9, 2014 at 10:16

2 Answers 2

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); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thak you very much! This is one big failure from me, sorry for inconvenience
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.