troubleshooting Question

Why does HeapAlloc() allocates more memory than I ask it to under Vista, but not under XP?

Avatar of meadowsps
meadowsps asked on
Microsoft DevelopmentCC++
12 Comments1 Solution2502 ViewsLast Modified:

We have some DLL code that we developed which has been running for years under XP with no problem. The basic problem seems to be that the routine HeapSize() returns a different value under Vista than it did under XP, or that HeapAlloc() allocates more than the number of bytes specified, we are not sure which one.

You see, in our code, we often allocate zero-length pointers that are destined to be filled with data later on. We rely upon the call to HeapSize() to return the correct size of the allocated pointer, and if the pointer is a zero-length pointer, then we expect a zero value to be returned so we know the buffer has yet to be filled with any data.

On Windows XP, this has worked flawlessly. However, on Vista, it seems that when allocating a zero-length pointer, the value returned from HeapSize() is often >0, typically it is a '1'.

Here is a small snippet of sample code:

            unsigned char * dataPtr = 0;
            int32 pointerSize = 0;
            dataPtr = (unsigned char *) HeapAlloc(GetProcessHeap(), 0, 0);
            pointerSize = HeapSize( GetProcessHeap(), 0, dataPtr );
In the above series of calls, the pointerSize value is returned as a  '1', even though the allocated memory was specified to be zero.

We have tried explicitly setting the length of the ponter to zero immediately after the call to HeapAlloc(), and then checking the size. In this case, the really odd thing is on the first call to HeapSize(), the size is correctly returned as a 0. However, all subsequent calls to HeapSize return a value of '8'.
We have no explanation for the behavior, other than perhaps some strange Vista issue related to zero-length pointers. The documentation for HeapAlloc() says that it will allocate "at least" the number of bytes requested. Not sure what that means. Does this mean you cannot rely upon the allocated block being exactly the same as the requested size? That might explain what is going on.

Thanks for your help... JK
Senior Software Engineer (Avast)

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 12 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 12 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros