2

I am doing a program which reads 3x3 matrices.

#include <stdio.h>
#include <stdlib.h>

typedef struct { 
    int row;
    int col;
    long **tab;
} matr;

int SIZE = 3;

void *emalloc(size_t size) {
    void *memory = malloc(size);

    if (!memory) {
        fprintf(stderr, "ERROR: Failed to malloc.\n");
        exit(1);
    }

    return memory;
}

void file_to_matrix(FILE *path_matr, matr *m) {
    long **matrix = (long**) emalloc(SIZE * sizeof(long*));
    for (int i = 0; i < SIZE; i++) matrix[i] = (long*) emalloc(SIZE * sizeof(long));

    char line[4];
    fscanf(path_matr, " %[^\n]", line);

    // This code does not give SEGFAULT
    // for (int i = 0; i < SIZE; i++) {
    //  fscanf(path_matr, "%ld%ld%ld", &matrix[i][0], &matrix[i][1], &matrix[i][2]);
    // }

    // The code below gives SEGFAULT
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            fscanf(path_matr, "%ld", &matrix[i][j]);
        }
    }

    m->row = SIZE;
    m->col = SIZE;
    m->tab = matrix;
}

int main(int args, char *argv[]) {
    FILE *path_matr = fopen(argv[1], "r");

    /*Getting the matrices*/
    int n_matr; // Number of matrices
    fscanf(path_matr, "%d", &n_matr);
    matr *matrices = emalloc(n_matr * sizeof(matr));

    for (int i = 0; i < n_matr; i++) {
        file_to_matrix(path_matr, &matrices[i]);
    }

    for (int i = 0; i < n_matr; i++)
        free(matrices[i].tab);
    free(matrices);
    fclose(path_matr);

    return 0;
}

Notice there are two for-loops in file_to_matrix function. One version gives segmentation fault, the other does not. Why? Funny thing is: if I enable -O2, both version works.

Compiled with gcc -std=c11 test.c -o test -g && ./test in.txt (gcc version 4.9.2).

in.txt:

3
∗∗∗
11 12 1444
21 22 23
31 32 33
∗∗∗
11 12 13
21 22 23
31 32 33
∗∗∗
11 12 13
21 22 23
31 31 33
∗∗∗

P.S.: The code I posted here is part of another code, from which I removed some blocks (such as checking the number of arguments, fopen's return, etc) for simplicity. The issues I describe here also happens with the original code.

2
  • 2
    Side issue: you are not freeing the memory you have allocated for your matrices (or closing path_matr or returning a value from main()). Jun 14, 2018 at 20:25
  • 1
    I just compiled and ran both versions on gcc 8.1.0 x86_64. Everything is ok and both matrices are read correctly. Probably some buffer overflow leading to undefined behaviour.
    – MadEqua
    Jun 14, 2018 at 21:39

1 Answer 1

6

I think you're causing a buffer overflow with

char line[4];
fscanf(path_matr, " %[^\n]", line);

Try changing to

fscanf(path_matr, " %3[^\n]", line);

or mitigating the potential for overflow in some other way.

Character width

Ensure you are using * (unicode 0x2a) and not (unicode 0xE2 0x88 0x97) for the separators. The larger character width in the latter causes scanf() to terminate early. (When I copied and pasted the sample input on your question it included the wider character.)

When you do this the maximum field width specifier for scanf() isn't strictly necessary - but I would still use it anyway.

Optimization

When you increase optimization with -O2 matrix is optimized out - so the program doesn't even try to write to it.

P.S.: you should check the return value from fopen().

8
  • 1
    It seems changing to fscanf(path_matr, " %3[^\n]", line); indeed solved the segmentation fault. Do you have any idea why using the first version works? Jun 14, 2018 at 21:32
  • 2
    UB is UB. You read off the end of an array and wild and interesting things occur. Perhaps the array had more room. Alignment changes? Good/Bad Luck... Jun 14, 2018 at 21:34
  • 2
    @EnzoNakamura It is probably something to do with optimization. One version keeps working because the value was in a register and it ignored you overwriting it in memory. Maybe. As Michael says, undefined behavior.
    – Zan Lynx
    Jun 14, 2018 at 21:35
  • 2
    @EnzoNakamura: Hi. The first version doesn't work for my either (using gcc 6.3.0). The vital point is that the address of matrix is being overwritten, so - even if the first loop doesn't cause a segmentation fault - that's just a coincidence. The first version might not segfault, but have you tried reading the values from matrix afterwards? Jun 14, 2018 at 21:41
  • Ok, something really weird is going on. @DavidCollins, I printed the matrices with the first version loop (without the '%3' in fscanf). It prints correctly. I realized that the '%3' in fscanf got away with the segmentation fault in my computer. However, the program prints the matrices wrongly (with both versions of for-loop). So maybe some kind of UB is still up? Yet, after I read the line of *** with fscanf(path_matr, " %3[^\n]", line), I did printf("%s\n", line) and it only printed '*'. I did printf("%d\n", line[0]) and it printed negative number. Any ideas someone? Jun 15, 2018 at 0:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.