简体   繁体   中英

segmentation fault when reading from file to buffer

I need to read a file and then send it through a socket, but fread crash for some reason. Any idea?

//Get file length
fseek(fd, 0, SEEK_END);
int fileLen=ftell(fd);
fseek(fd, 0, SEEK_SET);

//Allocate memory
buf=(char *)malloc(fileLen+1)* sizeof(char));
if (!buf)
{
    fprintf(stderr, "Memory error!");
}
rewind(fd);

fread((void *)buf, strlen(buf)+1, 1, fd);

There are quite a few basic confusions in that code.

  • ftell() returns long , not int . Also it should be const , since the file's size is assumed not to change while we read it.
  • There's no need to call rewind() and use fseek() to offset 0.
  • Don't cast the return value of malloc() in C .
  • You are not dealing with strings, so don't add one for some "terminator".
  • Don't scale allocations by sizeof (char) , that's always 1.
  • Check that the allocation succeeds before relying on the result.
  • Don't cast the buffer pointer to void * in fread() , that's completely pointless.
  • Use the file length in the fread() , calling strlen() on an undefined pointer is undefined behavior.
  • Verify that the fread() succeeds.
fread((void *)buf, strlen(buf)+1, 1, fd);

should be

fread((void *)buf, 1, fileLen, fd);

You did not initialized the contents of buf , so strlen(buf) will not return the correct length of buf .

By the way, buf=(char *)malloc(fileLen+1)* sizeof(char)); should be buf=(char *)malloc(fileLen); , there is no need to allocate that extra byte, and sizeof(char) always returns 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM