Frage

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);
War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top