malloc in C

The malloc() function is part of the standard library and takes a number as an argument. When executed, malloc() attempts to retrieve designated memory segments from the heap and returns a pointer that is the starting point for the memory reserved

#include <stdio.h>
#include <stdlib.h>
main()
{
 char *name;
 name = (char *) malloc(80 * sizeof(char));
 if ( name == NULL )
 printf("\nOut of memory!\n");
 else
 printf("\nMemory allocated.\n");
}

The malloc() function returns a null pointer if it is unsuccessful in allocating memory

Managing Strings with malloc()

#include <stdio.h>
#include <stdlib.h>
main()
{
 char *name;
 name = (char *) malloc(80*sizeof(char));
 if ( name != NULL ) {
 printf("\nEnter your name: ");
 gets(name);
 printf("\nHi %s\n", name);
 } // end if
}

Leave a Comment