Sams Teach Yourself C in 21 Days

(singke) #1
LISTING20.2 malloc.c. Using malloc()to determine how much memory is
free
1: /* Using malloc() to determine free memory.*/
2:
3: #include <stdio.h>
4: #include <stdlib.h>
5:
6: /* Definition of a structure that is
7: 1024 bytes (1 kilobyte) in size.) */
8:
9: struct kilo {
10: struct kilo *next;
11: char dummy[1020];
12: };
13:
14: int FreeMem(void);
15:
16: int main( void )
17: {
18:
19: printf(“You have %d kilobytes free.\n”, FreeMem());
20: return 0;
21: }
22:
23: int FreeMem(void)
24: {
25: /*Returns the number of kilobytes (1024 bytes)
26: of free memory. */
27:
28: long counter;
29: struct kilo *head, *current, *nextone;
30:
31: current = head = (struct kilo*) malloc(sizeof(struct kilo));
32:
33: if (head == NULL)
34: return 0; /*No memory available.*/
35:
36: counter = 0;
37: do
38: {
39: counter++;

572 Day 20

If you are running an operating system that allows multiple programs to be
running at once, then you will want to quit all other programs before run-
ning listing 20.2. If you use all of the memory in your system, your system
can lock up or do other unpredictable things.

Caution


INPUT

32 448201x-CH20 8/13/02 11:16 AM Page 572

Free download pdf