INF: Notes on Memory Allocation

ID Number: Q10758

3.00 4.00 5.00 5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

In Microsoft C versions 3.0, 4.0, 5.0, 5.1, 6.0, 6.0a, 6.0ax, and C/C++

version 7.0, the functions malloc() and calloc(), when used in the large

model, seem to lose large chunks of memory whenever the segment value of

the allocated memory changes.

For example, if two requests for 16K are made, and the segment value

of the returned pointer for the second request is different than that

of the first, the distance between the pointers will be about 24,000

bytes.

More Information:

The reason these memory allocation functions operate in this way is

the size of the request and the way that malloc() operates in large

model combine to produce this result. Malloc() is tuned to handle a

large number of (relatively) small allocations very quickly. To do

this task, malloc() wants to avoid having to go to MS-DOS often to

request memory.

Thus, when malloc() does go to MS-DOS it takes large chunks of memory

at a time (8K is default size) and subsequent allocations are made out

of this block until malloc()is full. When the allocation request is

greater than 8K, an extra 8K chunk that is only partially used may be

allocated. If the next request doesn't fit in the remaining space in a

given segment, the allocator must get a new segment, which, in this

case is allocated nearly 8K above the last byte of the previous

allocation. Reducing the size of this chunk will also reduce the size

of the wasted space.

This procedure can be done by declaring the following in your program

and setting it to a smaller value:

extern unsigned int _amblksiz;

The smaller the value, the less wasted space, but the slower malloc

will be. When large blocks are being allocated, there are fewer calls

to malloc()by definition, so the speed loss is not as critical.

Setting _amblksiz = 2 in the test program reduces the loss in space to

about 42 bytes without a noticeable degradation in the program.

Additional reference words: 5.00 5.10 6.00 6.00a 6.00ax 7.00