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

মডুলার C প্রোগ্রামিং (Modular C Programming)

কেবল মাত্র একটি ফাংশন দিয়ে কোনো বড়ো জটিল সমস্যা সমাধানের চেষ্টা করা ভাল প্রোগ্রামিংয়ের পদ্ধতি নয়। সঠিক পদ্ধতি হ'ল সমস্যাটিকে কয়েকটি ছোট ছোট এবং সরল টুকরো করে ফেলা যাতে তা আরও বিশদে বোঝা যায় । তারপরে এই ছোট এবং সরল সমস্যাগুলি সমাধান করার জন্য ছোট ছোট ফাংশন ব্লক তৈরি করা এবং পরে সেগুলি নিয়মানুযায়ী সংযোজিত করা ।

Programming Style

Programming Style

In this section, I'd like to briefly highlight some points that will help you write clean programs that can easily be read, understood, and maintained.

Exercises : Answer the following Question

To help solidify your understanding of this hour's lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the Workshop before you move to the next lesson.

Question and Answer

    Q Is the C preprocessor part of the C compiler?

    A No. The C preprocessor is not part of the C compiler. With its own line-oriented grammar and syntax, the C preprocessor runs before the compiler in order to handle named constants, macros, and inclusion of files.

Compiling Your Code Under Conditions

Compiling Your Code Under Conditions

You can select portions of your C program that you want to compile by using a set of preprocessor directives. This is useful, especially when you're testing a piece of new code or debugging a portion of code.