Valgrind gives an error “Invalid read of size 4”

  Kiến thức lập trình

I’m reading float data in from a file and Valgrind gives the error “Invalid read of size 4”. I’m a new user of Valgrind and don’t understand why I get this error.

My code is:

int main() 
{
    N = 220928;
    std::vector<std::complex<float>> rxTmp(N);

    FILE *fid;
    char fn[] = "data.bin";
    fid = fopen(fn, "rb");

    std::size_t ct = fread(&rxTmp[0],4,N,fid);

    fclose(fid);  

    return 0;
}

The code compiles and executes without error but Valgrind gives the invalid read.

==41376== 1 errors in context 1 of 1:
==41376== Invalid read of size 4
==41376==    at 0x77E0180: fread (in /usr/lib64/libc-2.17.so)
==41376==    by 0x423F67: main (main.cc:77)
==41376==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

where line 77 is the fread statement.
The file size is correct; there are 220928*4 floats in the file.

Reading in any value less than N results in the same Valgrind error.

I tried changing the number of elements read to less than the number of elements in the file and still get the Valgrind error

6

I was not able reproduce the issue after adding basic error checking of the fopen() call. I also changed the fread() size argument from 4 to sizeof rxTmp[0] which is 8 on my system.

#include <complex>
#include <cstdio>
#include <iostream>
#include <vector>

int main() {
    std::size_t N = 220928;
    std::vector<std::complex<float> > rxTmp(N);
    FILE *fid = fopen("data.bin", "rb");
    if(!fid) {
        std::cerr << "Could not open filen";
        return 1; // fclose(NULL) is undefined
    }
    std::size_t ct = fread(&rxTmp[0],sizeof rxTmp[0],N,fid);
    fclose(fid);  
    return 0;
}

2

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT