C malloc()

The malloc() function is defined in the stdlib.h header file. It helps to allocate the specified memory and returns a pointer to it. The malloc() function can't set allocated memory to zero.


void *malloc(size_t size); #where sizes hould be in bytes

 

malloc() Parameters: 

The malloc() function takes two parameters. This function helps to allocate memory blocks dynamically. We can assign the malloc function to any pointer.

Parameter Description Required / Optional
size This is the size of the memory block, in bytes Required

malloc() Return Value

The return value of malloc() function is a pointer to the allocated memory.

Input Return Value
success pointer to memory
fails NULL

Examples of malloc() 

Example 1: Working of malloc() function in C?


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

int main()
{
   char *s;

   /*memory allocation */
   s = (char *) malloc(12);
   strcpy(s, "programming");
   printf("String = %s,  Address = %u\n", s, s);

   /* Reallocating memory */
   s = (char *) realloc(s, 20);
   strcat(s, ".com");
   printf("String = %s,  Address = %u\n", s, s);

   free(s);
   
   return(0);
}

Output:


String = programming, Address = 355090448
String = programming.com, Address = 355090448

Example 2: How malloc() works in C?


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

int main (){
  int *p;
  p = malloc(15 * sizeof(*p)); 
    if (p != NULL) {
      *(p + 5) = 480; 
      printf("6th integer value is %d",*(p + 5));
    }
}

Output:


6th integer value is 480