I have two identical functions for allocating a contiguous block of memory for a matrix, one being for an int
the other for a double
. See below:
double** alloc_2d_double(int rows, int cols) {
double* data = (double*)malloc(rows * cols * sizeof(double));
double** array = (double**)malloc(rows * sizeof(double));
int i;
for (i = 0; i < rows; i++) {
array[i] = &(data[cols*i]);
}
return(array);
}
int** alloc_2d_int(int rows, int cols) {
int* data = (int*)malloc(rows * cols * sizeof(int));
int** array = (int**)malloc(rows * sizeof(int));
int i;
for (i = 0; i < rows; i++) {
array[i] = &(data[cols * i]);
}
return(array);
}
The double
function works just fine but the int function fails with malloc()
: memory corruption. Why does the int function fail when the double doesn't?
This code is for an mpi program and the double
function sees calls with parameters 25, 25 and 60, 60 and the int
function sees calls with parameters 27, 22 and 100, 100.
Any advice would be greatly appreciated!