Using realloc() Function in C

By: Charles Emailed: 1610 times Printed: 2076 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The realloc() function changes the size of a block of memory that was previously allocated with malloc() or calloc(). The function prototype is

void *realloc(void *ptr, size_t size);

The ptr argument is a pointer to the original block of memory. The new size, in bytes, is specified by size. There are several possible outcomes with realloc():

  • If sufficient space exists to expand the memory block pointed to by ptr, the additional memory is allocated and the function returns ptr.
  • If sufficient space does not exist to expand the current block in its current location, a new block of the size for size is allocated, and existing data is copied from the old block to the beginning of the new block. The old block is freed, and the function returns a pointer to the new block.
  • If the ptr argument is NULL, the function acts like malloc(), allocating a block of size bytes and returning a pointer to it.
  • If the argument size is 0, the memory that ptr points to is freed, and the function returns NULL.
  • If memory is insufficient for the reallocation (either expanding the old block or allocating a new one), the function returns NULL, and the original block is unchanged.

Listing below demonstrates the use of realloc().

Using realloc() to increase the size of a block of dynamically allocated memory.

1: /* Using realloc() to change memory allocation. */
2:
3: #include <stdio.h>
4: #include <stdlib.h>
5: #include <string.h>
6:
7: main()
8: {
9:     char buf[80], *message;
10:
11:     /* Input a string. */
12:
13:     puts("Enter a line of text.");
14:     gets(buf);
15:
16:     /* Allocate the initial block and copy the string to it. */
17:
18:     message = realloc(NULL, strlen(buf)+1);
19:     strcpy(message, buf);
20:
21:     /* Display the message. */
22:
23:     puts(message);
24:
25:     /* Get another string from the user. */
26:
27:     puts("Enter another line of text.");
28:     gets(buf);
29:
30:     /* Increase the allocation, then concatenate the string to it. */
31:
32:     message = realloc(message,(strlen(message) + strlen(buf)+1));
33:     strcat(message, buf);
34:
35:     /* Display the new message. */
36:     puts(message);
37:     return(0);
38: }
Enter a line of text.
This is the first line of text.
This is the first line of text.
Enter another line of text.
This is the second line of text.
This is the first line of text.This is the second line of text.

ANALYSIS: This program gets an input string on line 14, reading it into an array of characters called buf. The string is then copied into a memory location pointed to by message (line 19). message was allocated using realloc() on line 18. realloc() was called even though there was no previous allocation. By passing NULL as the first parameter, realloc() knows that this is a first allocation.

Line 28 gets a second string in the buf buffer. This string is concatenated to the string already held in message. Because message is just big enough to hold the first string, it needs to be reallocated to make room to hold both the first and second strings. This is exactly what line 32 does. The program concludes by printing the final concatenated string.


C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(8)


1. View Comment

Very good

View Tutorial          By: take at 2010-03-29 07:47:01
2. View Comment

good explanation

View Tutorial          By: Naresh Kumar at 2010-10-25 00:28:18
3. View Comment

This is a bad example, it does not check if the allocation of memory worked. Also, you'd normally use malloc for the first allocation.

View Tutorial          By: Erik at 2011-02-12 07:16:20
4. View Comment

Looks good, but don't use gets(). gets() is responsible for the world's problems. Use fgets() and specify the buffer. Otherwise, some nasty fellow will be inclined to overstep the bounds of your array.

View Tutorial          By: Luke at 2011-11-21 09:03:38
5. View Comment

Really clear and lucid explanation abt realloc .... thnx a bunch!!!!!!!!

View Tutorial          By: metarus208 at 2012-01-01 14:25:25
6. View Comment

DON'T USE GETS!!!!!!!!!!!!!!! IT'S DANGEROUS!

View Tutorial          By: Caterpillar at 2012-04-23 13:22:42
7. View Comment

Shouldn't you call free() on the allocated memory block?
Yes, you should !!!
The example of this articles leads to a memory leak.


View Tutorial          By: Ritchie at 2012-05-09 14:14:49
8. View Comment

Never use gets for taking inputs from users. Your program is prone to Buffer Overflows.

View Tutorial          By: Aneesh Dogra at 2012-07-20 04:08:32

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Charles
arraycopy example in Java
Action listeners in JSF
Automatically Including Preludes and Codas in JSP
Using realloc() Function in C
Handling multiple buttons in HTML Form in Struts
Fopen and Getc implementation program in C
Pointers to Structures example program in C
Pointers vs. Multi-dimensional Arrays in C
getch and ungetch in C
Bitwise Operators in C
Variables and Arithmetic Expressions in C
Differences between JavaServer Faces technology and Struts
assert() example program in C++
'double buffering' Sample program in J2ME
Converting Default Function Arguments in C++ to Java

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
UNIX read and write system calls sample program in C
lseek() sample program in C
Using memset(), memcpy(), and memmove() in C
Find square and square root for a given number in C
Listing Files and Directories sample program in C
Open, Creat, Close, Unlink system calls sample program in C
perror() Function - example program in C
Calculator in C
Variables and Arithmetic Expressions in C
Conditional Expressions in C
goto and labels in C
Static Variables in C
Macro Substitution using #define in C
#if, #elif, #ifndef, #ifdef in C (Conditional Inclusion)
Binary Tree - (Self-referential Structures) example program in C
Most Emailed Articles (in C)
Macro Substitution using #define in C
Address Arithmetic and pointers in C
Printing a simple histogram in C
The for statement in C
Symbolic Constants using #define in C
register Variables in C
Pointers to Structures example program in C
Using realloc() Function in C
Using memset(), memcpy(), and memmove() in C
Formatting with printf in C
Find square and square root for a given number in C
Getting Started with C
Variables and Arithmetic Expressions in C
Character Counting sample program in C
Arguments - Call by Value in C