The MASM Forum Archive 2004 to 2012

General Forums => The Workshop => Topic started by: stanhebben on September 12, 2006, 05:56:48 AM

Title: Program closes when calling LocalAlloc (or HeapAlloc)
Post by: stanhebben on September 12, 2006, 05:56:48 AM
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]
Title: Re: Program closes when calling LocalAlloc (or HeapAlloc)
Post by: hutch-- on September 12, 2006, 06:07:10 AM
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.
Title: Re: Program closes when calling LocalAlloc (or HeapAlloc)
Post by: Shantanu Gadgil on September 12, 2006, 07:01:17 AM
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
Title: Re: Program closes when calling LocalAlloc (or HeapAlloc)
Post by: stanhebben on September 12, 2006, 11:18:45 AM
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.