Thursday, July 14, 2011

malloc and free

Malloc requires one argument - the number of bytes you want to allocate dynamically.
If the memory allocation was successful, malloc will return a void pointer - you can assign this to a pointer variable, which will store the address of the allocated memory.
If memory allocation failed (for example, if you're out of memory), malloc will return a NULL pointer.
Passing the pointer into free will release the allocated memory - it is good practice to free memory when you've finished with it.
This example will ask you how many integers you'd like to store in an array. It'll then allocate the memory dynamically using malloc and store a certain number of integers, print them out, then releases the used memory using free


#include <stdio.h>
#include <stdlib.h> // required for the malloc and free functions

int main(int argc, char **argv {
     int number;
     int *ptr;
     int i;


     printf("How many ints would you like store ?\n");
     scanf("%d", &number);


     ptr = malloc(number*sizeof(int)); /* allocate memory */

     if(ptr != NULL) {
           for(i=0 ; i<number ; i++) {
                *(ptr+i) = i;
           }

           for(i=number ; i>0 ; i--) {
                printf("%d\n", *(ptr+(i-1))); /* print out in reverse order */
           }

           free(ptr); /* free allocated memory */
           return 0;
     }
     else {
           printf("\nMemory allocation failed - not enough memory.\n");
           return 1;
     }
     return 0;
}

Output if I entered 3: 
How many ints would you like store? 3
2
1
0

When I first wrote the example using a Borland compiler, I had to cast the returned pointer like this

ptr = (int *)malloc(number*sizeof(int);

The above example was tested in MSVC++ and gcc 4.x.x but try casting the pointer if your compiler displays an error.

No comments:

Post a Comment