2 ms·
Not going to talk about the actual bug(s), but... why is it trying to NUL-terminate the buffer full of binary ("rb") data? Also, sizeof(char)? That's 1 by defin
by Joker_vD 3y ago
Not going to talk about the actual bug(s), but... why is it trying to NUL-terminate the buffer full of binary ("rb") data? Also, sizeof(char)? That's 1 by definition.
Actually, no, let's talk about the bug. What's with people's obsession of eliminating local temporaries and working straight with pointer-to-result?
char *buff = malloc(n + 1);
if (fread(buff, 1, n, f) != n) {
free(buff);
fclose(f);
return false;
}
buff[n] = '\0';
*data = buff;
ok:
fclose(f);
return true;
This way, data won't contain a freed pointer when reading fails.
- bjourne 3y ago"rb" because you don't want Windows to open the file in translated mode and munging its contents. Null-termination so that the same code can deal with both binary and text files. And I prefer all mallocs to follow the pattern malloc(sizeof(tp)*n) because it's less hassle than thinking about what types' sizes may vary. This rabbit hole is endless and we haven't even started covering my use of fseek/ftell/rewind!
- Joker_vD 3y agoYeah, "fread(buff, 1, result_from_ftell, f)" can have some pretty strange effects on the buff's content if CHAR_BIT != 8.