Home > Blockchain >  C memory issues on file import
C memory issues on file import

Time:10-09

I'm writing a pretty long program that includes a lot of data importing and I started getting an error munmap_chunk(): invalid pointer. I looked around and this seemed to be caused by free() functions. I then commented all such functions in my program and the error still happened. All I could find is that this is probably caused by memory issues and that I should run Valgrind. So I did, and it returned me a whole bunch of errors mostly related to my import functions. In particular this one:

void import_bn(int depth, int idx, float pdata[4][depth]) {

    // [0][:] is gamma, [1][:] is beta, [2][:] is moving mean, [3][:] is moving variance

    // Define name from index
    char name[12]; // maximum number of characters is "paramxx.csv" = 11
    sprintf(name, "param%d.csv", idx);

    // open file
    FILE *fptr;
    fptr = fopen(name, "r");
    if (fptr == NULL) {
        perror("fopen()");
        exit(EXIT_FAILURE);
    }

    char c = fgetc(fptr); // generic char
    char s[13];           // string, maximum number of characters is "-xxx.xxxxxxx" = 12
    char* a;              // pointer for strtof

    for (int t = 0; t < 4;   t) { // type
    for (int d = 0; d < depth;   d) { // depth

        //skip S
        if (c == 'S') {c = fgetc(fptr);c = fgetc(fptr);}

        // write string
        for (int i=0; c != '\n';   i) {
            s[i] = c;
            c = fgetc(fptr);
        }

        float f = strtof(s,&a); // convert to float
        pdata[t][d] = f;     // save on array
        c = fgetc(fptr);
    }}

    fclose(fptr);
}

The file this is supposed to be opening always has the format:

0.6121762
1.5259982
1.6705754
0.6907939
0.5508608
1.2173915
S
2.2555487
2.9224594
-1.6631562
-1.2156529
1.6944195
1.0379710
...etc

So basically they are float32s separated by '\n' and each batch is separated by an "S". This represents a multidimensional array, and in the case of this function there are always exactly 4 batches, but sizes vary.

One of the errors that appeared a lot in Valgrind was Use of uninitialised value of size 8 at the float f = strtof(s,&a); line. Am I using strtof() wrong?

The full results from Valgrind can be found here: https://pastebin.com/rKwTUgut

CodePudding user response:

The first argument to strtof() must be a null-terminated string. You're not adding a null terminator after the // write string loop.

        int i;
        for (i=0; c != '\n';   i) {
            s[i] = c;
            c = fgetc(fptr);
        }
        s[i] = '\0';
  • Related