C library functions -malloc()

C Standard Library - <stdlib.h>

Description

C Library Functionsvoid *malloc(size_t size)Allocate the required memory space and return a pointer to it.

Declaration

The following is the declaration of the malloc() function.

void *malloc(size_t size)

Parameter

  • size-- The size of the memory block, in bytes.

Return Value

This 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.

Example

#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char *str; /*Initial memory allocation*/ str = (char *) malloc(15); strcpy(str, "example"); 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 results:

String = example,  Address = 3662685808
String = example.com,  Address = 3662685808

C Standard Library - <stdlib.h>

other extensions