Using free() Function in C

By: Daniel Malcolm Emailed: 1607 times Printed: 2076 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

When you allocate memory with either malloc() or calloc(), it is taken from the dynamic memory pool that is available to your program. This pool is sometimes called the heap, and it is finite. When your program finishes using a particular block of dynamically allocated memory, you should deallocate, or free, the memory to make it available for future use. To free memory that was allocated dynamically, use free(). Its prototype is

void free(void *ptr);

The free() function releases the memory pointed to by ptr. This memory must have been allocated with malloc(), calloc(), or realloc(). If ptr is NULL, free() does nothing. Sample program below demonstrates the free() function.

Using free() to release previously allocated dynamic memory.

1: /* Using free() to release allocated dynamic memory. */
2:
3: #include <stdio.h>
4: #include <stdlib.h>
5: #include <string.h>
6:
7: #define BLOCKSIZE 30000
8:
9: main()
10: {
11:     void *ptr1, *ptr2;
12:
13:     /* Allocate one block. */
14:
15:     ptr1 = malloc(BLOCKSIZE);
16:
17:     if (ptr1 != NULL)
18:         printf("\nFirst allocation of %d bytes successful.",BLOCKSIZE);
19:     else
20:     {
21:         printf("\nAttempt to allocate %d bytes failed.\n",BLOCKSIZE);
22:         exit(1);
23:     }
24:
25:     /* Try to allocate another block. */
26:
27:     ptr2 = malloc(BLOCKSIZE);
28:
29:     if (ptr2 != NULL)
30:     {
31:         /* If allocation successful, print message and exit. */
32:
33:         printf("\nSecond allocation of %d bytes successful.\n",
34:                BLOCKSIZE);
35:         exit(0);
36:     }
37:
38:     /* If not successful, free the first block and try again.*/
39:
40:     printf("\nSecond attempt to allocate %d bytes failed.",BLOCKSIZE);
41:     free(ptr1);
42:     printf("\nFreeing first block.");
43:
44:     ptr2 = malloc(BLOCKSIZE);
45:
46:     if (ptr2 != NULL)
47:         printf("\nAfter free(), allocation of %d bytes successful.\n",
48:                BLOCKSIZE);
49:     return(0);
50: }
First allocation of 30000 bytes successful.
Second allocation of 30000 bytes successful.

AANALYSIS: This program tries to dynamically allocate two blocks of memory. It uses the defined constant BLOCKSIZE to determine how much to allocate. Line 15 does the first allocation using malloc(). Lines 17 through 23 check the status of the allocation by checking to see whether the return value was equal to NULL. A message is displayed, stating the status of the allocation. If the allocation failed, the program exits. Line 27 tries to allocate a second block of memory, again checking to see whether the allocation was successful (lines 29 through 36). If the second allocation was successful, a call to exit() ends the program. If it was not successful, a message states that the attempt to allocate memory failed. The first block is then freed with free() (line 41), and a new attempt is made to allocate the second block.

You might need to modify the value of the symbolic constant BLOCKSIZE. On some systems, the value of 30000 produces the following program output:

First allocation of 30000 bytes successful.
Second attempt to allocate 30000 bytes failed.
Freeing first block.
After free(), allocation of 30000 bytes successful.

On systems with virtual memory, of course, allocation will always succeed.

 


DO free allocated memory when you're done with it.

DON'T assume that a call to malloc(), calloc(), or realloc() was successful. In other words, always check to see that the memory was indeed allocated.



C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(7)


1. View Comment

Thanks. Helped me save few hours

View Tutorial          By: Balan at 2008-04-07 18:25:08
2. View Comment

thanks bro it helped me to answer my faculty question

View Tutorial          By: kasmin at 2010-01-08 08:11:32
3. View Comment

thanks

View Tutorial          By: nitin at 2010-03-29 01:02:57
4. View Comment

thanks for to solve my doubts

View Tutorial          By: puttaswamy B S at 2010-09-28 00:45:47
5. View Comment

Thanks for to solve my doubt.

View Tutorial          By: ANJILAIAH at 2010-10-08 09:46:11
6. View Comment

thanks becase i am very confuse what is work how to use

View Tutorial          By: arvind at 2011-01-09 14:41:42
7. View Comment

Can you tell me what will happen when I use a free function call to release the memory allocated to a memory block on ONE of the MULTIPLE pointers pointing to that memory block, eg

void *ptr1,*ptr2,*ptr3;
ptr1=ptr2=ptr3=malloc(1000);
free(ptr1);

in this case, what will happen if I try to access ptr2 and ptr3, and for that matter, ptr1, before I have assigned NULL to them, and after the above code?


View Tutorial          By: Neo at 2012-04-04 16:21:35

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Daniel Malcolm
javac options in Java
Operator Precedence in Java
Calling Multiple Listeners in JSF
Using free() Function in C
ForwardAction in Struts
Listing Files and Directories sample program in C
Binary Tree - (Self-referential Structures) example program in C
A simple program using EL in JSP
Command-line Arguments in C
Example Calculator program in C - describing use of External Variables in C
Assignment Operators and Expressions in C
The for statement in C
JSF Basics
assert() Versus Exceptions in C++
RMS Basics in J2ME

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Using memset(), memcpy(), and memmove() in C
Listing Files and Directories sample program in C
perror() Function - example program in C
Open, Creat, Close, Unlink system calls sample program in C
Using free() Function in C
assert() Function Example program in C
scanf and sscanf sample program in C
UNIX read and write system calls sample program in C
Sum of the elements of an array in C
Printing a simple histogram in C
lseek() sample program in C
Sorting an integer array in C
Find square and square root for a given number in C
Functions in C
goto and labels in C
Most Emailed Articles (in C)
Address Arithmetic and pointers in C
Macro Substitution using #define in C
Pointers to Structures example program in C
Getting Started with C
Variables and Arithmetic Expressions in C
register Variables in C
Trigonometric, Hyperbolic, Exponential and Logarithmic Functions in C
Printing a simple histogram in C
Symbolic Constants using #define in C
Arguments - Call by Value in C
Conditional Expressions in C
Functions returning non-integer values in C
Recursion in C
Tutorial on Complicated Declarations in C
Standard Input and Output in C