1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define oops(s) { perror((s)); exit(1); }
int main()
{
double *tab;
double *tmp;
double **tab2;
double **tmp2;
int i,j;
int n = 10;
int increment = 5;
int current_size=0;
int isecret;
/*initial dynamic allocation*/
tab=malloc(sizeof(double)*n);
if(tab==NULL){free(tab);oops("Error: malloc()");}
tab2 = malloc(sizeof(double*)*n);
if(tab2==NULL){free(tab2);oops("Error: malloc()");}
for(i=0;i<n;i++){
tab2[i] = malloc(sizeof(double)*3);
if(tab2[i]==NULL){free(tab2[i]);oops("Error: malloc()");}
}
/*----loop starts----*/
isecret = rand() % 100 + 1;
isecret = 30;
for(i=0;i<isecret;i++){
printf("current_size=%d n=%d\n",current_size,n);
if(current_size>=n){ /*if initial allocation filled up*/
printf("realloc at %d\n",n+increment);
tmp=realloc(tab,sizeof(double)*(n+increment));
if(tmp==NULL){free(tab);oops("Error: realloc()");}
tmp2=realloc(tab2,sizeof(double*)*(n+increment));
if(tmp==NULL){free(tab);oops("Error: realloc()");}
for(j=0;j<n;j++){
tmp2[j] = realloc(tab2,sizeof(double)*3);
if(tmp2[j]==NULL){free(tab2[j]);oops("Error: malloc()");}
}
n += increment;
tab = tmp;
tab2 = tmp2;
}
tab[i] = rand() % 10;
tab2[i][0] = rand() % 20;
tab2[i][1] = rand() % 200;
tab2[i][2] = rand() % 200;
current_size++;
}
/*----loop ends----*/
/*if realloc'ed too much memory*/
if(n>current_size){
/*realloc down to the right value*/
printf("final realloc at %d\n",current_size);
tmp = realloc(tab,sizeof (double) * current_size);
if(tmp==NULL){free(tab);oops("reallocc() error");}
tab = tmp;
tmp2 = realloc(tab2,sizeof (double*) * current_size);
if(tmp2==NULL){free(tab2);oops("reallocc() error");}
for(j=0;j<3;j++){
tmp2[j] = realloc(tab2,sizeof(double)*3);
if(tmp2[j]==NULL){free(tab2[j]);oops("Error: malloc()");}
}
tab2 = tmp2;
}
for(i=0;i<current_size;i++){
printf("tab[%d]=%1.1f\n",i,tab[i]);
for(j=0;j<3;j++){printf("tab2[%d][%d]=%1.1f\n",i,j,tab2[i][j]);}
}
free(tab);
free(tmp);
free(tmp2);
for(j=0;j<3;j++){
free(tmp2[j]);
}
return 0;
}/*end main*/ |
Partager