Easy Tutorial
❮ C Examples Sum Natural Numbers C Exercise Example21 ❯

C Library Function - malloc()

C Standard Library - <stdlib.h>

Description

The C library function void *malloc(size_t size) allocates the required memory space and returns a pointer to it.

Declaration

Here is the declaration for the malloc() function.

void *malloc(size_t size)

Parameters

Return Value

The function returns a pointer to the allocated memory. If the request fails, it returns NULL.

Example

The following example demonstrates the usage of the malloc() function.

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

int main()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialpro");
   printf("String = %s,  Address = %u\n", str, str);

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

   free(str);

   return(0);
}

Let's compile and run the above program, which will produce the following result:

String = tutorialpro,  Address = 3662685808
String = tutorialpro.org,  Address = 3662685808

C Standard Library - <stdlib.h>

❮ C Examples Sum Natural Numbers C Exercise Example21 ❯