Here's my code:
#include <stdio.h>
#include <stdlib.h>
#define M 5
#define N 3
double **create_matrix(int m, int n);
void destroy_matrix(double **matrix, int m);
int main(void)
{
int i = 0, j = 0;
int x = 0;
double **matrix;
matrix = create_matrix(M, N);
while (i < M) {
j = 0;
while (j < N) {
printf("%4.0f", *(*(matrix + j) + i) = j);
j++;
}
putchar('\n');
i++;
}
destroy_matrix(matrix, M);
return 0;
}
double **create_matrix(int m, int n)
{
int i = 0;
double **matrix;
if ((matrix = (double **) malloc(sizeof(double *) * m)) != NULL) {
while (i < m)
if ((*(matrix + i++) = (double *) malloc(sizeof(double) * n)) == NULL)
return NULL;
return matrix;
} else
return NULL;
}
void destroy_matrix(double **matrix, int m)
{
int i = 0;
while (i < m)
free((void *) *(matrix + i++));
free((void *) matrix);
}
- Allocating, initializing and printing the matrix works.
- Allocating, not initializing and freeing works.
- Allocating, initializing AND freeing does NOT work.
Backtrace:
*** glibc detected *** [file]: free(): invalid next size (fast): 0x0000000001e7d040 ***
Followed by a memory map.
I searched for similar problems but couldn't find one fitting my situation, nor could I derive mine from them.