Reallocating Memory
It is possible many times while you are programming that you want to reallocate memory. This is done with the realloc function. The realloc function takes two parameters, the base address of memory you want to resize, and the amount of space you want to reserve and returns a pointer to the base address.
Suppose we have reserved space for a pointer called msg and we want to reallocate space to the amount of space it already takes up, plus the length of another string then we could use the following.
msg = (char *)realloc(msg, (strlen(msg) + strlen(buffer) + 1)*sizeof(char));
The following program illustrates the use of malloc, realloc and free. The user enters a series of strings that are joined together. The program stops reading strings when an empty string is entered.
#include <string.h>
#include <malloc.h>
int main()
{
char buffer[80], *msg;
int firstTime=0;
do
{
printf("\nEnter a sentence: ");
gets(buffer);
if (!firstTime)
{
msg = (char *)malloc((strlen(buffer) + 1) *
sizeof(char));
strcpy(msg, buffer);
firstTime = 1;
}
else
{
msg = (char *)realloc(msg, (strlen(msg) +
strlen(buffer) + 1) * sizeof(char));
strcat(msg, buffer);
}
puts(msg);
} while(strcmp(buffer, ""));
free(msg);
return 0;
}
The output of the program will be as follows:
Enter a sentence: Once upon a time
Once upon a time
Enter a sentence: there was a king
Once upon a timethere was a king
Enter a sentence: the king was
Once upon a timethere was a kingthe king was
Enter a sentence:
Once upon a timethere was a kingthe king was |
|