Turboc 2.0 malloc/free/coreleft

Ted H. Emigh emigh at ncsugn.ncsu.edu
Fri Feb 1 06:38:53 AEST 1991


In article <1991Jan30.172158.2769 at ux1.cso.uiuc.edu > bloomqui at osiris.cso.uiuc.edu (Kim Bloomquist) writes:
 >I'm trying to write a Turbo C 2.0 program on a Zenith 386 that
 >reports the amount of memory (RAM) available after performing
 >certain operations.  The following program produces the output 
 >shown below:
 >
 >---------------------------- tst.c --------------------------
 >#include <stdio.h>
 >#include <stdlib.h>
 >#include <alloc.h>
 >main()
 >{
 >	unsigned long n;
 >	char *s;
	char t[80];      /*   ADD THIS LINE   */
 >
 >	n = coreleft();
 >	printf("ram left = %lu bytes free\n", n);
        printf("string t: ");
	scanf(t);
	n = coreleft();
	printf("ram left = %lu bytes free\n", n);
 >	if ((s = (char *) malloc(80)) == NULL)
 >	{
 >		printf("allocation failed\n");
 >		exit(0);
 >	}
 >	printf("buffer allocated\n");
 >	n = coreleft();
 >	printf("ram left = %lu bytes free\n", n);
 >	printf("string: ");
 >	gets(s);
 >	free((void *) s);
 >	printf("buffer deallocated\n");
 >	n = coreleft();
 >	printf("ram left = %lu bytes free\n", n);
 >}


This slight modification will give you the correct answers.  A couple of points

1)  coreleft() does not return the number of bytes available for malloc'ing.
    What it does return is the number of bytes below the lowest allocated
    block.  To test this, malloc a huge chunk, then a small chunk.  free the
    large chunk.  coreleft will still give a small number.  You can even
    malloc some more without coreleft changing!!!

2)  For Turbo-C (and possibly others), stdin is not opened until the first
    reference to it.  Opening a file (and stdin/stdout) takes some space off
    the heap.

4)  If you have TC++, you can use the heapwalk functions to get a better idea
    of memory available, although it will not be contiguous.  This may or may
    not be particularly useful.



More information about the Comp.lang.c mailing list