Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - malloc()

C library function - malloc()

C Standard Library - <stdlib.h> C Standard Library -

Description

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

Declaration

Here is the declaration of the malloc() function.


void *malloc(size_t size)

Parameters

Return Value

This function returns a pointer to the allocated block of memory. If the request fails, it returns NULL.

Example

The following example demonstrates the use 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

,

"

runoob

"

)

;

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's compile and run the above program, which will produce the following result:


String = runoob,  Address = 3662685808
String = runoob.com,  Address = 3662685808

C Standard Library - <stdlib.h> C Standard Library -