Kurosaki_Ichigo Kurosaki_Ichigo - 3 months ago 13
C Question

My program crashes when using free function (C) on array

My program works if I don't free the memory I allocated dinamically, but when I try to free it, it crashes. I am running my code on Dev-C++ and the error message is not helpful: a problem has made the program stop working.
The problem is at the end of the code. If I take of the freeing part, the program works just fine. Here is a sample input:

5
2.3
1.4 8.2
3.1 2.0 7.7
5.3 6.1 4.4 1.2
5.5 6.1 3.0 2.3 4.9


The code:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int main(void) {
int ordem;
scanf("%d", &ordem);
double **vetor; //apontador para apontador (jagged array)
double soma = 0;
int elementos;
elementos = (ordem*ordem + ordem) / 2;
vetor = malloc(ordem * sizeof(double*)); //o primeiro endereço do vetor é seu local de memória, que define quantos pointers ele terá (ordem)
int n, m;
for (n = 0; n < ordem; n++) {
*(vetor + n) = malloc(n * sizeof(double));
}
for (n = 0; n < ordem; n++) {
for (m = 0; m <= n; m++) {
scanf("%lf", *(vetor + n) + m);
soma = soma + *(*(vetor + n) + m);
}
}
double media = soma / (double) elementos;
double aux = 0;
for (n = 0; n < ordem; n++) {
for (m = 0; m <= n; m++) {
aux = aux + pow((media - vetor[n][m]), 2);
}
}
double desvio = sqrt(aux / ((double)elementos));
for (n = 0; n < ordem; n++) {
for (m = 0; m <= n; m++) {
printf("%.12lf ", (vetor[n][m] - media) / desvio);
}
printf("\n");
}
printf("\n%.12lf %.12lf \n", media, desvio);

for (n = 0; n < ordem; n++) {
free(*(vetor + n));
}
free(vetor);

return 0;
}


And that's pretty much it. I don't know how to fix this. I don't think dealloc has the same effect. I prefer to stick to free. New information I discovered: for the sample input, I can free((vetor + 0)), ((vetor + 1)) and (*(vetor + 2)), but not 3 and 4. That means the vector somehow has a problem on these two.

Answer

Change this:

for (n = 0; n < ordem; n++) {
    *(vetor + n) = malloc(n * sizeof(double));
}

to this:

for (n = 0; n < ordem; n++) {
    *(vetor + n) = malloc((n + 1) * sizeof(double));
}

The reason is that n is ZERO in the first iteration, so you are requesting malloc() to allocate zero bytes for you..

BTW, here is what I usually use for not making such kind of mistakes: 2d-dynamic-array-c.

Output:

C02QT2UBFVH6-lm:~ gsamaras$ gcc -Wall main.c 
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
5
2.3
1.4 8.2
3.1 2.0 7.7
5.3 6.1 4.4 1.2
5.5 6.1 3.0 2.3 4.9
-0.892202112506 
-1.307537578672 1.830552610141 
-0.523015031469 -1.030647267895 1.599810684493 
0.492249441383 0.861436522419 0.076913975216 -1.399834348932 
0.584546211642 0.861436522419 -0.569163416599 -0.892202112506 0.307655900864 

4.233333333333 2.166923061753
C02QT2UBFVH6-lm:~ gsamaras$