C Memory Management Functions: using realloc() function
Reallocate memory for more input storage
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info:
To do: Reallocate memory for more memory storage
To show: The realloc() C function usage - the dynamic memory allocation
/* Playing with realloc(). Store user input in an array */
#include <stdio.h>
#include <stdlib.h>
#define INITIAL_SIZE 5;
int main(void)
{
int *Arr, *temp;
int limit, input, n = 0, r, i;
/* Initially, allocate some space for Arr */
limit = INITIAL_SIZE;
Arr = (int *) malloc (limit * sizeof(int));
printf("The allocated memory is sizeof(limit * sizeof(int)) = %d bytes\n", sizeof(limit * sizeof(int)));
printf("Or sizeof(Arr) = %d bytes\n", sizeof(Arr));
/* Do some verification, if fail */
if (Arr == NULL)
{
/* Display the error message */
fprintf(stderr, "malloc() failed!\n");
/* Exit with the error code */
exit(1);
}
/* array loop */
printf("Enter numbers, 1 per line. End with ctrl-D\n");
while(1)
{
printf("Next number: ");
/* r = scanf("%d", &input); */
r = scanf_s("%d", &input, sizeof(input));
fflush(stdin);
/* verify the input */
if(r <1)
break;
/* get more space for Arr using realloc() */
if(n >= limit)
{
printf("More than 5 elements per loop, reallocating the storage... \n");
limit = 2 * limit;
temp = (int *)realloc(Arr, limit * sizeof(int));
printf("The added memory storage is %d bytes\n", sizeof(temp));
/* Verify again... */
if(temp == NULL)
{
fprintf(stderr, "realloc() failed!\n");
exit(1);
}
else
printf("realloc() is OK lol, proceed with more input...\n");
Arr = temp;
}
Arr[n] = input;
n++;
}
/* Trim Arr down to size */
temp = (int *)realloc(Arr, n*sizeof(int));
/* Verify... */
if(temp == NULL)
{
fprintf(stderr, "realloc() fails lol!\n");
exit(1);
}
Arr = temp;
printf("\nContents of the array Arr:\n");
/* Print the array */
for(i = 0; i < n; i++)
{
printf("%2d ", Arr[i]);
}
printf("\n");
return 0;
}
Output example:
The allocated memory is sizeof(limit * sizeof(int)) = 4 bytes
Or sizeof(Arr) = 4 bytes
Enter numbers, 1 per line. End with ctrl-D
Next number: 12
Next number: 23
Next number: 34
Next number: 45
Next number: 56
Next number: 67
More than 5 elements per loop, reallocating the storage...
The added memory storage is 4 bytes
realloc() is OK lol, proceed with more input...
Next number: 98
Next number: 87
Next number: 76
Next number: 65
Next number: 54
More than 5 elements per loop, reallocating the storage...
The added memory storage is 4 bytes
realloc() is OK lol, proceed with more input...
Next number: ^D
Contents of the array Arr:
12 23 34 45 56 67 98 87 76 65 54
Press any key to continue . . .