INFO: Memory Management Via Malloc()

ID: Q90531


The information in this article applies to:


SUMMARY

In the C Run-time (CRT) libraries which are included with the Win32 SDK (LIBC.LIB, LIBCMT.LIB, and CRTDLL.LIB), malloc() and its related functions map directly to the system Heap APIs. They don't do the sub-allocation that they do under MS-DOS/Windows. In many ways, using the C Run-time under Windows NT is the same as using the Win32 API, because the CRT routines often call the equivalent Win32 API directly.

In the CRT libraries that are included with Microsoft Visual C++ 32-bit Edition (LIBC.LIB, LIBCMT.LIB, and MSVCRT.LIB), malloc() does use a heap allocation scheme which is similar to but more complicated than the 16-bit heaps were. The 4-bytes that precede the heap entry point to internal data structures. You should not rely on this information, since we may want to make changes in the future in order to provide a faster heap.

The information in the remainder of this article applies only to the Win32 SDK CRT.


MORE INFORMATION

The C Run-time heap manager searches for the first available block of memory that is large enough to satisfy the request. When more memory is needed, the heap manager will grow the heap. When a block of memory is freed, the manager checks the previous and following block to see whether either or both can be combined with the newly freed block to form a contiguous free block. In either case, freed memory is re-used if possible.

Internal CRT information such as block size and status (used or free) is kept in a header in the bytes preceding the block, not in a separate location, such as a table. You should not rely on this information, since it may change in future versions of the CRT.

Problems occur if you corrupt the header information of a block by writing beyond the previous allocated block. When the block with the corrupted header is freed, the heap manager will consider the memory that the header happens to point to as the next block when it attempts to combine adjacent free blocks. The system will crash with an exception in RtlExAllocateHeap() upon the next malloc or free involving this memory.

The blocks are contiguous, so overwriting one block when writing to a different block is not considered writing outside the program's memory space. The C Run-time heap manager doesn't make sure that writes do not extend beyond the end of an allocated block. This would be too great of a speed penalty, considering how often the heap is used.

In order to debug heap problems, use the heap diagnostic functions.

Note that the same problem can occur with APIs such as LocalAlloc() and GlobalAlloc().

Additional query words:


Keywords          : kbCRT kbVC100 kbVC200 kbVC210 kbVC400 kbVC500 
Version           : WINDOWS NT:1.0,2.0,2.1,4.0,5.0;
Platform          : NT WINDOWS 
Issue type        : kbinfo 

Last Reviewed: July 5, 1999