• Home
  • Tutorials
  • Interviews
  • Info Seed
  • Forums
  • Projects
  • Links
  • Contact Us
C Language
C POINTERS
MEMORY MANAGEMENT
INTRODUCTION
FIXED MEMORY
STACK MEMORY
HEAP MEMORY
Illustration with simple program
Functions to manage HEAP MEMORY
MEMORY ALLOCATION
MEMORY ALLOCATION-II
MEMORY ALLOCATION-III
MEMORY ALLOCATION-IV
Illustrations of MEMORY ALLOCATION
Illustration I
Illustration-I Contd..
Illustration-I Contd..
Illustration-I Contd..
Illustration II
Illustration-II Contd..
Illustration-II Contd..
Illustration III
Illustration IV
FRAME POINTER

 

 

Functions to manage heap memory

The functions to manage heap memory which are included in the directory  #include <stdlib.h> are:

 malloc():

void * malloc (size_t size);

As we see from the prototype of the malloc function that we have to pass the number of bytes required as parameter to the malloc function and the function returns the starting address of the allocated apace as void pointer. As the void pointer is returned hence we have to typecast the pointer as the type we require. E.g.

If we need 6 bytes for intergers we type cast the memory as

Int* x;

x=(int*)malloc(6);

If we are storing char variables in the allocated space then we do as:

Char* y;

y=(char*)malloc(6);

calloc():

The prototype of the function is as:

void * calloc (size_t nr, size_t size);

nr is number of variables of the required type and size is the number of bytes required for that type

and this function automatically initializes the memory allocated to zero.

e.g.

if we need memory for 6 integers

int* x;

x=(int*)calloc (6, sizeof(int) );

 if we need memory for 6 characters

char* x;

x=(char*)calloc (6, sizeof(char) );

NOTE: If any of the two functions is not able to allocate memory then it returns a NULL pointer.

realloc():

The prototype of the realloc() function is

void * realloc (void *ptr, size_t size);

This function is used to redefine the size already allocated. Suppose as I have already allocated memory for 6 integers in the previous example, now I want the space for the 8 integers then I do as:

X= (int*)realloc (x,8) ;

Free():

The prototype of the free() function is

void* free (void* ptr);

We write the following to free the memory of x:

free(x);

 

previous next
| Copyright © 2009 exploreroots- All Rights Reserved | Disclaimer |