C library function - malloc()


Advertisements

Description

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

Declaration

Following is the declaration for malloc() function.

void *malloc(size_t size)

Parameters

  • size − This is the size of the memory block, in bytes.

Return Value

This function returns a pointer to the allocated memory, or NULL if the request fails.

Example

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

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

int main () {
   char *str;

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

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

   free(str);
   
   return(0);
}

Let us compile and run the above program that will produce the following result −

String = tutorialspoint, Address = 355090448
String = tutorialspoint.com, Address = 355090448
stdlib_h.htm

Useful Video Courses


Video

JCL Online Training

12 Lectures 2 hours

Nishant Malik

Video

COBOL Online Training

12 Lectures 2.5 hours

Nishant Malik

Video

CRO Online Training

48 Lectures 6.5 hours

Asif Hussain

Video

Customer Service Online Training

12 Lectures 2 hours

Richa Maheshwari

Video

Cultivation of Crops

20 Lectures 3.5 hours

Vandana Annavaram

Video

Eclipse Online Training

44 Lectures 1 hours

Amit Diwan

Advertisements