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

C Library Function - realloc()

C Library Function - realloc()

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

realloc() is a function in the C standard library used to reallocate memory space. It is very important in dynamic memory management, especially when the size of already-allocated memory needs to be adjusted.

C library function **void realloc(void ptr, size_t size) Attempts to resize the memory block previously allocated by a call to malloc or calloc and pointed to by ptr the given pointer.

Declaration

The following is the declaration of the realloc() function:


void *realloc(void *ptr, size_t size)

Parameters

Return Value

Usage notes

Example

The following example demonstrates the use of the realloc() function.

Example 1

#include

<
stdio.h
#include
<
stdlib.h
#include
<
string.h
int
main
(
)
{
char
str

;

/*

Initial memory allocation

*/

str

=

(

char

)

malloc

(

15

)

;

strcpy

(

str

,

"

runoob

"

)

;

printf

(

"

String = %s, Address = %p

\

n

"

,

str

,

str

)

;

/*

Reallocating memory

*/

str

=

(

char

)

realloc

(

str

,

25

)

;

strcat

(

str

,

"

.com

"

)

;

printf

(

"

String = %s, Address = %p

\

n

"

,

str

,

str

)

;

free

(

str

)

;

return

(

0

)

;

}

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


String = runoob,  Address = 0x7fa2f8c02b10
String = runoob.com,  Address = 0x7fa2f8c02b10

Example 2

#include

#include

int

main

(

)

{

   

int

arr

=

malloc

(

5

sizeof

(

int

)

)

;

 

// Allocate memory for 5 integers

   

if

(

arr

==

NULL

)

{

       

printf

(

"Memory allocation failed\n"

)

;

       

return

1

;

   

}

   

// Fill the array

   

for

(

int

i

=

0

;

i

<

5

;

i

++

)

{

        arr

[

i

]

=

i

2

;

   

}

   

// Reallocate memory, resizing to 10 integers

   

int

new_arr

=

realloc

(

arr

,

10

sizeof

(

int

)

)

;

   

if

(

new_arr

==

NULL

)

{

       

printf

(

"Reallocation failed\n"

)

;

       

free

(

arr

)

;

 

// Free the original memory on failure

       

return

1

;

   

}

   

// Fill the new portion

   

for

(

int

i

=

5

;

i

<

10

;

i

++

)

{

        new_arr

[

i

]

=

i

2

;

   

}

   

// Print the new array

   

for

(

int

i

=

0

;

i

<

10

;

i

++

)

{

       

printf

(

"%d "

,

new_arr

[

i

]

)

;

   

}

   

free

(

new_arr

)

;

 

// Finally, free the memory

   

return

0

;

}

Notes

Common Use Cases

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