In università ho scritto un programma per un esercitazione senza avere alcun problema (gcc a 32bit).
Torno a casa, provo a compilare e a testare (amd64, sistema x86_64 con gcc che compila quindi a 64 bit) ma quando arrivo al primo ciclo nella matrix_free ho un errore di doble free or corruption. Posto qui sotto una versione minimale dell'applicazione dove è possibile riprodurre il bug:
codice:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct strMatrix {
int r, c;
float **elem;
};
typedef struct strMatrix *Matrix;
//Prototypes
Matrix matrix_init_sequence(int rows, int columns, float start, float dx);
void matrix_free(Matrix *m);
//Definitions
Matrix matrix_init_sequence(int rows, int columns, float start, float dx) {
Matrix matrix = (Matrix) malloc(sizeof(struct strMatrix));
int r, c;
matrix->r = rows; matrix->c = columns;
matrix->elem = (float**)calloc(rows, sizeof(float));
for (r=0; r<rows; r++) {
matrix->elem[r] = (float*)calloc(columns, sizeof(float));
for (c=0; c<columns; c++, start+= dx) matrix->elem[r][c] = start;
}
return matrix;
}
void matrix_free(Matrix *m) {
int r;
if (*m == NULL) return;
for (r=0; r< (*m)->r; r++) {
printf("%d\n",r ); //debug
free( (*m)->elem[r] ); //<<= errore qui al primo loop
printf("fatto;\n"); //debug
}
printf("\n");
free((*m)->elem);
free(*m); *m = NULL;
}
int main(){
Matrix b = matrix_init_sequence(4, 2, 1.0, 0.0);
matrix_free(&b);
return 0;
}
codice:
$ gcc -lm -o test test.c && ./test
Tuttavia, se forzo gcc a compilare a 32 bit specificando -m32, allora il programma fila liscio e non si presenta alcun problema...
Non ci sto capendo più niente, qualcuno ha un'idea? Thx.