I'm using a function which integrates a polynomial which is given to the function as a pointer argument. Inside the function I use a malloc
in order to allocate memory for the integrated polynomial which will be returned.
The problem is, I cannot free it before returning it to the main function, cause then I would be returning nothing. But if I free it after returning it then I'm obviously doing nothing because the program will return to the main function before reading the free.
Here's the function.
double * integrar(int n, double *dp, double *mitjana) {
double *p, mitj = 0;
int i;
p = (double *)malloc((n + 2)*sizeof(double));
if(p == NULL) {printf("\nError de memoria.\n"); exit(1);}
p[0] = 1;
for(i = 1; i <= n + 1; i++)
p[i] = dp[i - 1]/i;
for(i = 0; i <= n + 1; i++)
mitj += p[i];
mitj = mitj/(n + 2);
*mitjana = mitj;
return p; }
I need to somehow free p. Here's the main function:
int main(void) {
int n, k, i, j;
double mitjmax, mitjaux, **p;
mitjmax = 0;
printf("Dona el grau del polinomi.\n");
scanf("%d", &n);
printf("\nDona el nombre de vegades que el vols integrar.\n");
scanf("%d", &k);
p = (double **)malloc((k + 1)*sizeof(double *));
if(p == NULL) {printf("\nError de memoria.\n"); exit(1);}
for(i = 0; i < k + 1; i++) {
p[i] = (double *)malloc((n + 1 + i)*sizeof(double));
if(p[i] == NULL) {printf("\nError de memoria.\n"); exit(1);}
}
printf("\nDona el polinomi.\n");
for(i = 0; i <= n; i++)
scanf("%le", &p[0][i]);
for(i = 0; i <= n; i++)
mitjmax += p[0][i];
mitjmax = mitjmax/(n + 1);
for(i = 1; i <= k; i++) {
p[i] = integrar(n + i - 1, p[i - 1], &mitjaux);
if(mitjaux > mitjmax)
mitjmax = mitjaux;
}
for(i = 0; i <= k; i++) {
printf("grau %d:", i + n);
for(j = 0; j <= n + i; j++)
printf("%11.4le ", p[i][j]);
printf("\n");
}
printf("El maxim de les mitjanes dels coeficients: %le\n", mitjmax);
for(i = 0; i <= k; i++)
free(p[i]);
free(p);
return 0;
}