I am getting some weird pointer-related errors that I do not understand how can happen and how to solve it. Since I am new to C any good coding practice advice is also appreciated.
typedef struct matrix {
int n;
int m;
int **data;
int *inverses;
} Matrix;
Matrix m_new(int n, int m, int *inverses) {
int **data = malloc(n);
for (int k = 0; k < n; k ) {
int *row = malloc(m 1);
*row = k;
*(data k) = row;
// print_arr(*data); - introduced for debugging purposes
}
Matrix mat = {
.n = n,
.m = m,
.data = data,
.inverses = inverses,
};
return mat;
}
void print_arr(int *arr) {
int len = *(arr-1);
printf("len: %d\n", len);
}
Here, I am going to use this matrix for Gaussian Elimination over the integers mod some number, that's why I have the inverses array, and I use int **
, so that I can swap rows easily later. For arrays represented as int *
I use the -1th entry to store the length of the array. I got some weird bugs, so I wrote a small function to get the length of an array (print_arr) and check the first array in data. I got the following(for n=m=5):
len: 0
len: 0
len: 0
len: 0
len: -1219680380
Which I find really weird, because it seems like that something is changing in the last iteration, but I don't know why.
CodePudding user response:
Your allocations are too small. You need to multiply the number of elements by the size of the elements to compute how much memory to allocate:
int **data = malloc(n * sizeof (int *));
int *row = malloc((m 1) * sizeof (int));
With your current code, you overflow your too-small buffers and cause undefined behavior.