codescracker


c

C free()



« Previous Function Next Function »


free()

The free() function returns the memory pointed to by ptr to the heap. This makes the memory available for future allocation.

It is imperative that free() only be called with a pointer that was previously allocated using one of the dynamic allocation system's functions. Using an invalid pointer in the call most likely will destroy the memory management mechanism and possibly cause a system crash. If you pass a null pointer, free() performs no operation.

free() Syntax

Following is the syntax of the free() function :

#include<stdlib.h>
void free(void *ptr);

free() Example

Following program allocates room for the strings entered by the user and then frees the memory :

#include<stdlib.h>
#include<stdio.h>
#include<conio.h>

void main()
{
	clrscr();
	
	char *str[100];
	int i;
	for(i=0; i<100; i++)
	{
		if((str[i] = malloc(128)) == NULL)
		{
			printf("Allocation Error\n");
			exit(1);
		}
		gets(str[i]);
	}
	
	/* now free the memory */
	for(i=0; i<100; i++)
	{
		free(str[i]);
	}
	
	getch();
}

« Previous Function Next Function »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test