Tuesday, August 23, 2011

using calloc and malloc : sample c code

/*
An example using calloc and malloc memory allocation function   in C and and freeing the memory using free function
*/
#include <stdio.h>
#include <stdlib.h> // required for the malloc, calloc and free

int main(int argc, char **argv) {

      float *calloc1, *calloc2, *malloc1, *malloc2;
      int i;

      calloc1 = calloc(3sizeof(float)); /* might need to cast */
      calloc2 = calloc(3sizeof(float));
      malloc1 = malloc(3 * sizeof(float));
      malloc2 = malloc(3 * sizeof(float));

      if(calloc1!=NULL && calloc2!=NULL && malloc1!=NULL && malloc2!=NULL) {
            for(i=0 ; i<3 ; i++) {
                  printf("calloc1[%d] holds %05.5f, ", i, calloc1[i]);
                  printf("malloc1[%d] holds %05.5f\n", i, malloc1[i]);
                  printf("calloc2[%d] holds %05.5f, ", i, *(calloc2+i));
                  printf("malloc2[%d] holds %05.5f\n", i, *(malloc2+i));
            }

            free(calloc1);
            free(calloc2);
            free(malloc1);
            free(malloc2);

            return 0;
      }
      else {
            printf("Not enough memory\n");
            return 1;
      }
      return 0;
}

/*
 * OutPut:
 *
 calloc1[0] holds 0.00000, malloc1[0] holds -431602080.00000
 calloc2[0] holds 0.00000, malloc2[0] holds -431602080.00000
 calloc1[1] holds 0.00000, malloc1[1] holds -431602080.00000
 calloc2[1] holds 0.00000, malloc2[1] holds -431602080.00000
 calloc1[2] holds 0.00000, malloc1[2] holds -431602080.00000
 calloc2[2] holds 0.00000, malloc2[2] holds -431602080.00000
 */

No comments:

Post a Comment