Submitted by Anonymous (not verified) on Sun, 03/10/2013 - 20:36

The realloc() Function

The realloc() function gives you a means to change the size of a piece of memory space allocated by the malloc() function, the calloc() function, or even itself.

The syntax for the realloc() function is

#include <stdlib.h>
void *realloc(void *block, size_t size);


Here block is the pointer to the start of a piece of memory space previously allocated. size specifies the total byte number you want to change to. The realloc() function returns a void pointer.

The realloc() function returns a null pointer if it fails to reallocate a piece of memory space.

The realloc() function is equivalent to the malloc() function if the first argument passed to realloc() is NULL. In other words, the following two statements are equivalent:

ptr_flt = realloc(NULL, 10 * sizeof(float));
ptr_flt = malloc(10 * sizeof(float));

Also, you can use the realloc() function as the free() function. You do this by passing 0 to realloc() as its second argument. For instance, to release a block of memory pointed to by a pointer ptr, you can either call the free() function like this:

free(ptr);

or use the realloc() function in the following way:

realloc(ptr, 0);

The program in Listing 17.4 demonstrates the use of the realloc() function in memory reallocation.
 

TYPE
Listing 17.4. Using the realloc() function.


1:  /* 17L04.c: Using the realloc() function */
2:  #include <stdio.h>
3:  #include <stdlib.h>
4:  #include <string.h>
5:  /* function declaration */
6:  void StrCopy(char *str1, char *str2);
7:  /* main() function */
8:  main()
9:  {
10:    char *str[4] = {"There's music in the sighing of a reed;",
11:                    "There's music in the gushing of a rill;",
12:                    "There's music in all things if men had ears;",
13:                    "There earth is but an echo of the spheres.\n"
14:                   };
15:    char *ptr;
16:    int i;
17:
18:    int termination = 0;
19:
20:    ptr = malloc((strlen(str[0]) + 1) * sizeof(char));
21:    if (ptr == NULL){
22:      printf("malloc() failed.\n");
23:      termination = 1;
24:    }
25:    else{
26:      StrCopy(str[0], ptr);
27:      printf("%s\n", ptr);
28:      for (i=1; i<4; i++){
29:        ptr = realloc(ptr, (strlen(str[i]) + 1) * sizeof(char));
30:        if (ptr == NULL){
31:          printf("realloc() failed.\n");
32:          termination = 1;
33:          i = 4;    /* break the fro loop */
34:        }
35:        else{
36:          StrCopy(str[i], ptr);
37:          printf("%s\n", ptr);
38:        }
39:      }
40:    }
41:    free(ptr);
42:    return termination;
43: }
44: /* function definition */
45: void StrCopy(char *str1, char *str2)
46: {
47:    int i;
48:
49:    for (i=0; str1[i]; i++)
50:       str2[i] = str1[i];
51:    str2[i] = `\0';
52: }


The following output is obtained by running the executable 17L04.exe:

OUTPUT

C:\app>17L04
There's music in the sighing of a reed;
There's music in the gushing of a rill;
There's music in all things if men had ears;
There earth is but an echo of the spheres.
C:\app>

ANALYSIS

The purpose of the program in Listing 17.4 is to allocate a block of memory space to hold a character string. There are four strings in this example, and the length of each string may vary. I use the realloc() function to adjust the size of the previously allocated memory so it can hold a new string.

As you can see in lines 10_13, there are four character strings containing a lovely poem written by Lord Byron. (You can tell that I love Byron's poems.) Here I use an array of pointers, str, to refer to the strings.

A piece of memory space is first allocated by calling the malloc() function in line 20. The size of the memory space is determined by the (strlen(str[0])+1)*sizeof(char) expression. As mentioned earlier, because the C function strlen() does not count the null character at the end of a string, you have to remember to allocate one more piece of memory to hold the full size of a string. The sizeof(char) expression is used here for portability, although the char data type is 1 byte long on most computers.

Exercise 4 at the end of this lesson asks you to rewrite the program in Listing 17.4 and replace the malloc() and free() functions with their equivalent formats of the realloc() functions.

If the malloc() function doesn't fail, the content of the first string pointed to by the str[0] pointer is copied to the block memory allocated by malloc(). To do this, a function called StrCopy() is called in line 26. Lines 45_52 give the definition of StrCopy().

The for loop, in lines 28_39, copies the remaining three strings, one at a time, to the block of memory pointed to by ptr. Each time, the realloc() function is called in line 29 to reallocate and adjust the previously allocated memory space based on the length of the next string whose content is about to be copied to the memory block.

After the content of a string is copied to the memory block, the content is also printed out (see lines 27 and 37).

In this example, a block of memory space is allocated and adjusted based on the length of each of the four strings. The realloc() function, as well as the malloc() function, does the memory allocation and adjustment dynamically.

Related Items

Adding More Expressions into for

Adding More Expressions into for

The C language allows you to put more expressions into the three expression fields in the for statement. Expressions in a single expression field are separated by commas.

The Null Statement

The Null Statement

Looping Under the for Statement

Looping Under the for Statement

The general form of the for statement is

for (expression1; expression2; expression3) {
   statement1;
   statement2;
   .
   .
   .
}

Using Nested Loops

Using Nested Loops

You can put a loop inside another one to make nested loops. The computer will run the inner loop first before it resumes the looping for the outer loop.

Listing 7.7 is an example of how nested loops work.

 

The do-while Loop

The do-while Loop

You may note that in the for and while statements, the expressions are set at the top of the loop. However, in this section, you're going to see another statement used for looping,