INF: With /CP:1, _memavl() Still Shows Memory Available

ID Number: Q50472

5.10 6.00 6.00a 6.00ax | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

In Microsoft C versions 5.1, 6.0, 6.0a, and 6.0ax, using the /CP:1

(/CPARMAXALLOC - set maximum memory allocation) link option does not

always leave 1 byte available for allocation in the near heap

allocation. This problem becomes apparent when making a call to

_memavl().

Sample Code

-----------

/* Compile options needed: /CP:1 for linking

*/

/* test.c */

#include <malloc.h>

#include <stdio.h>

void main(void)

{

/* _amblksiz=1; */

/* The above line uncommented causes only a couple

of bytes to become available (see More Information). */

printf("Available memory in near heap = %d\n",

_memavl());

}

/* This program will show approximately 4K available when executed. */

More Information:

The _memavl() function itself is causing the near heap to grow. The

library functions _memavl(), _freect(), and _memmax() all require the

heap to be initialized for them to work properly. If the heap is not

initialized, then a malloc(0) call is made. The malloc() call causes

DGROUP to grow to the next _amblksiz boundary (8K by default). This

usually does not cause a problem because malloc() is usually called

either before or after the _memavl().

To reduce the amount of memory taken by DGROUP initialization, set

_amblksiz to some smaller amount in order for malloc(0) to grab only

as much it absolutely needs.

In C version 6.0, _memavl(), _freect(), and _memmax() do not make a

call to malloc() but there are other problems encountered when

attempting to limit the maximum near heap allocation:

- In small and medium memory models, printf(), as well as fprintf(),

will malloc() a 512-byte buffer from the near heap (in C 5.1, this

is static and wasted if stdout isn't used). This will happen with

any standard I/O-level library call because of the I/O buffer it

needs. (Predefined handles will do this as well.)

- argv[] and envp[] arrays are also put on the heap. However,

_amblksiz is adjusted down to about 1K when this is done in order

to minimize DGROUP growth.

Additional reference words: 5.10 6.00 6.00a 6.00ax