malloc( ) and free( )

malloc

malloc() and free()

  • allocates the requested memory and returns a pointer to it. (Dynamic memory allocation)
  • should #include<stdlib.h>
  • void *malloc(# of bytes): the function returns address of the memory.
  • void free(current_storage_pointer): de-allocate it to prevent memory leakage.

 

Example

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

int main(){
   int *p;
   p =(int *) malloc(sizeof(int));
   if(p==NULL){
      puts("Failed to allocate memory!");
   }else{
      *p = 20;
      printf("%d",*p);
      free(p);
   }
}

Example (Array)

#include<stdio.h>
#include<stdlib.h>
int main(){
   int size;
   printf("Enter the size of the array: ");
   scanf("%d", &size);
   int *a;
   a = (int *)malloc(size * sizeof(int));
   printf("\nEnter the values of the array: ");
   int i;
   for(i = 0; i < size; i++){
      scanf("%d", &a[i]);
   }
   printf("\nThe values in the array are: \n");
   for(i = 0; i < size; i++){
      printf("%d\t", a[i]);
   }
   free(a);
}

Leave A Comment

Your email address will not be published. Required fields are marked *