Releasing Allocated Memory with free()

Submitted by Anonymous (not verified) on Sun, 03/10/2013 - 20:30

Releasing Allocated Memory with free()

Because memory is a limited resource, you should allocate an exactly sized piece of memory right before you need it, and release it as soon as you don't need it.

The program in Listing 17.2 demonstrates how to release allocated memory by calling the free() function.
 

TYPE
Listing 17.2. Using the free() and malloc() functions together.


1:  /* 17L02.c: Using the free() function */
2:  #include <stdio.h>
3:  #include <stdlib.h>
4:  /* function declarations */
5:  void DataMultiply(int max, int *ptr);
6:  void TablePrint(int max, int *ptr);
7:  /* main() function */
8:  main()
9:  {
10:    int *ptr_int, max;
11:    int termination;
12:    char key = `c';
13:
14:    max = 0;
15:    termination = 0;
16:    while (key != `x'){
17:       printf("Enter a single digit number:\n");
18:       scanf("%d", &max);
19:
20:       ptr_int = malloc(max * max * sizeof(int));  /* call malloc() */
21:       if (ptr_int != NULL){
22:          DataMultiply(max, ptr_int);
23:          TablePrint(max, ptr_int);
24:          free(ptr_int);
25:       }
26:       else{
27:          printf("malloc() function failed.\n");
28:          termination = 1;
29:          key = `x';  /* stop while loop */
30:       }
31:       printf("\n\nPress x key to quit; other key to continue.\n");
32:       scanf("%s", &key);
33:    }
34:    printf("\nBye!\n");
35:    return termination;
36: }
37: /* function definition */
38: void DataMultiply(int max, int *ptr)
39: {
40:    int i, j;
41:
42:    for (i=0; i<max; i++)
43:       for (j=0; j<max; j++)
44:          *(ptr + i * max + j) = (i+1) * (j+1);
45: }
46: /* function definition */
47: void TablePrint(int max, int *ptr)
48: {
49:    int i, j;
50:
51:    printf("The multiplication table of %d is:\n",
52:            max);
53:    printf(" ");
54:    for (i=0; i<max; i++)
55:       printf("%4d", i+1);
56:    printf("\n ");
57:    for (i=0; i<max; i++)
58:       printf("----", i+1);
59:    for (i=0; i<max; i++){
60:       printf("\n%d|", i+1);
61:       for (j=0; j<max; j++)
62:         printf("%3d ", *(ptr + i * max + j));
63:    }
64: }


While the executable 17L02.exe is being run, I enter two integers, 4 and 2 (highlighted in the following output), to obtain a multiplication table for each; then I quit running the program by pressing the x key:

OUPUT

C:\app>17L02
Enter a single digit number:
4
The multiplication table of 4 is:
   1   2   3   4
 --------------
1| 1   2   3   4
2| 2   4   6   8
3| 3   6   9  12
4| 4   8  12  16
Press x-key to quit; other key to continue.
C
Enter a single digit number:
2
The multiplication table of 2 is:
   1   2
 ------
1| 1   2
2| 2   4
Press x-key to quit; other key to continue.
x
Bye!
C:\app>

ANALYSIS

The purpose of the program in Listing 17.2 is to build a multiplication table based on the integer given by the user. The program can continue building multiplication tables until the user presses the x key to quit. The program also stops execution if the malloc() function fails.

To show you how to use the free() function, the program allocates a temporary memory storage to hold the items of a multiplication table. As soon as the content of a multiplication table is printed out, the allocated memory is released by calling the free() function.

Lines 5 and 6 declare two functions, DataMultiply() and TablePrint(), respectively. The former is for performing multiplication and building a table, whereas the latter prints out the table on the screen. The definitions of the two functions are given in lines 38_45 and lines 47_64, respectively.

Inside the main() function, there is a while loop in lines 16_33 that keeps asking the user to enter an integer number (see lines 17 and 18) and then building a multiplication table based on the integer.

To hold the result of the multiplication, the statement in line 20 allocates a memory storage that has the size of max*max*sizeof(int), where the int variable max contains the integer value entered by the user. Note that the sizeof(int) expression gives the byte number of the int data type of the computer on which the program is being run.

If the malloc() function returns a null pointer, the return value of the main() function is set to 1 to indicate an abnormal termination (see line 28), and the while loop is stopped by assigning the key variable with `x' in line 29.

Otherwise, if the malloc() function allocates a memory storage successfully, the DataMultiply() function is called in line 22 to calculate each multiplication. The results are saved into the memory storage pointed to by the ptr_int pointer. Then the multiplication table is printed out by calling the TablePrint() function in line 23.

As soon as I no longer need to keep the multiplication table, I call the free() function in line 24 to release the allocated memory storage pointed to by the ptr_int pointer.

If I did not release the memory, the program would take more and more memory as the user keeps entering integer numbers to build more multiplication tables. Eventually, the program would either crash the operating system or be forced to quit. By using the free() and malloc() functions, I am able to keep running the program by taking the exact amount of memory storage I need, no more and no less.

Related Items

Adding More Expressions into for

Adding More Expressions into for

The C language allows you to put more expressions into the three expression fields in the for statement. Expressions in a single expression field are separated by commas.

The Null Statement

The Null Statement

Looping Under the for Statement

Looping Under the for Statement

The general form of the for statement is

for (expression1; expression2; expression3) {
   statement1;
   statement2;
   .
   .
   .
}

Using Nested Loops

Using Nested Loops

You can put a loop inside another one to make nested loops. The computer will run the inner loop first before it resumes the looping for the outer loop.

Listing 7.7 is an example of how nested loops work.

 

The do-while Loop

The do-while Loop

You may note that in the for and while statements, the expressions are set at the top of the loop. However, in this section, you're going to see another statement used for looping,