Question

I am writing a C program, in which I try to dynamically allocate a 2-dim array (or an array of arrays.) After the table is allocated I try to iterate over it, but it throws an error about illegal memory access and creates a coredump.

After some investigation I've found out a curious thing: the array I experiment with is 4x4, but when I set array[0][3] = 123; it sets both [0][3] and [1][0] positions to be 123. Exactly the same thing happens if I assign array[1][0] = 123;, as it sets both [0][3] and [1][0] to the rightside value. Similar assignment is done for any "border values", like [2][0] and [1][3]. I guess something must be wrong with my allocation, but I can't figure it out. I was pretty sure that this is the way to dynamically allocate multi-dim arrays and a bit of research confirmed it. Here is my code (I know it should be SSSCE but I can't provide it shorter and still show the problem):

typedef struct {
    int rows;
    int columns;
    double **data;
} matrix;


matrix* allocateMatrix(int inputRows, int inputColumns) {
    matrix *matrixPointer = calloc(1, sizeof(matrix));
    matrixPointer->rows = inputRows;
    matrixPointer->columns = inputColumns;
    #ifdef DOUBLE
        matrixPointer->data = calloc(inputRows, sizeof(double*));
    #else
        matrixPointer->data = calloc(inputRows, sizeof(float*));
    #endif
    if (matrixPointer->data == NULL) {
        printf("Error - inputRows value appears to be wrong.");
        return NULL;
    }

    int i, j;
    for (i = 0; i < inputRows; i++) {
    #ifdef DOUBLE
        matrixPointer->data[i] = calloc(inputColumns, sizeof(double));
    #else
        matrixPointer->data[i] = calloc(inputColumns, sizeof(float));
    #endif
        if (matrixPointer->data[i] == NULL) {
            printf("Error - inputColumns value appears to be wrong.");
            return NULL;
        }
    }
    matrixPointer->data[2][0] = 123;    //TEST CODE;

    return matrixPointer;
}

And some code to see the contents of such created array:

matrix *lol = allocateMatrix(4, 4); 
    int i, j;
    for (i = 0; i < lol->rows; i++)
            for (j = 0; j < lol->columns; j++)
                printf("%f ", lol->data[i][j]);

Is my memory allocation wrong, or maybe some other issue I fail to see. I would be grateful for any suggestions or help. Thank you in advance.

Was it helpful?

Solution

typedef struct {
    int rows;
    int columns;
    double **data;
} matrix;

This is the culprit. The DOUBLE macrodefinition was supposed to enable double precision through the code, but when the flag was not set the code still allocated double** data, causing possible segmentation faults. The correct code in this case should look like:

typedef struct {
    int rows;
    int columns;
    #ifdef DOUBLE
        double **data;
    #else
        float **data;
    #endif
} matrix;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top