Program closes when calling LocalAlloc (or HeapAlloc)

Started by stanhebben, September 12, 2006, 05:56:48 AM

Previous topic - Next topic

stanhebben

I am currently stuck at a very strange bug.

I'm writing a program which - at times - has to allocate some memory. Most allocations work fine, but at some point calling LocalAlloc causes my program to close. No message, no crash, it simply exits. LocalAlloc does not return at all. This is very strange, because memory usage is relatively low.

I think I've had this problem in past, requiring me to rewrite programs completely. But now I really want to know why this happens. Replacing LocalAlloc with a HeapAlloc equivalent doesn't make a difference. (because, I guess, LocalAlloc calls HeapAlloc internally)

Anyone had this problem in past?

The program is attached, and the problematic LocalAlloc is at line 882.

[attachment deleted by admin]

hutch--

Stan,

Have you tried GetLastError() directly after the allocation ? I get similar effects with some errors, the app just exits with no warning or error message.
Download site for MASM32      New MASM Forum
https://masm32.com          https://masm32.com/board/index.php

Shantanu Gadgil

Hi Stan,
I have also faced these "funny" bugs with Global/Local Alloc functions.

What was happening was that memory was not being allocated properly and the (next instruction) writing to the supposedly allocated  memory location was causing the program to crash.

What fixed it for me was locking the memory handle with GlobalLock.

The reaaally "funny" thing is that I have used GlobalAlloc/LocalAlloc many times after that *without* a lock on it and it has worked fine.

Anyway, do check if the locking thing works!

Regards,
Shantanu
To ret is human, to jmp divine!

stanhebben

Ok, I found the problem myself.

Because of a small mistake, the program did not allocate enough space. Result: the program wrote past the end of the allocated space, which must have been data used by LocalAlloc. Correcting this solved everything.

My conclusion: make sure you *never* write past the end of allocated blocks. Your program doesn't crash immediately, but next time you allocate something things can get messed up pretty bad.