A realloc example
Code:
#include <stdio.h>
#include <stdlib.h>
/* this is an example of the use of the realloc function */
/* the RESIZE is the amount of memory we want to extend by */
/* on each call. Too small, and realloc thrashes, wasting */
/* time, and potentially fragmenting memory. Too large, */
/* and we waste memory which won't be used */
/* You have to know some things about your data to make */
/* a good guess at this */
#define RESIZE 7
/* Typically this is either unknown, an estimate, or */
/* determined at run-time by some means */
#define MAX 53
int main ( ) {
int *int_array = NULL; /* MUST be initialised to NULL */
int max_i = 0; /* number of useable slots in the array */
int i;
for ( i = 0 ; i < MAX ; i++ ) {
if ( i >= max_i ) {
int *new;
max_i += RESIZE; /* get a bit more array */
printf("Extending array to %d slots\n", max_i );
new = realloc(int_array,max_i*sizeof(int));
if ( new == NULL ) {
/* panic - no memory left */
/* save and quit, or popup window saying no more */
} else {
/* update the array pointer */
/* realloc can move the memory to a whole new */
/* place in memory */
int_array = new;
}
}
/* use the array (which grows in size) */
int_array[i] = i;
}
/* just to show you it's there! */
for ( i = 0 ; i < MAX ; i++ ) {
printf("%d=%d\t", i, int_array[i] );
}
/* all done with the array now */
free(int_array);
return 0;
}