I've been writing the following bit of code, and someone had informed me that it runs of the risk of having a buffer overflow.
Now admittedly my knowledge of buffer overflows may be not be as robust as I would like, but I thought that a buffer overflow is when the data being written will not fit within the bounderies of the buffer and will spill over to adjacent memory location.
I assumed that the problem may be related to the fread, that it wouldn't be a safe function to use, but reading through the documentation doesn't seem to tell me that its unsafe like say strcpy() is compared to strncpy(). So I'm rather uncertain on where the problem could be located or how to handle it. And also if anyone has any suggestions on where I can go (or what book to read) that would help expand my knowledge on this subject or other vulnerability weaknesses, I would be appreciative.
bool readLong(FILE *f, long *n)
{
unsigned char *ptr,tmp;
if (fread(n,8,1,f) != 1)
return false;
ptr = (unsigned char *)n;
tmp = ptr[0];
ptr[0] = ptr[7];
ptr[7] = tmp;
tmp = ptr[1];
ptr[1] = ptr[6];
ptr[6] = tmp;
tmp = ptr[2];
ptr[2] = ptr[5];
ptr[5] = tmp;
tmp = ptr[3];
ptr[3] = ptr[4];
ptr[4] = tmp;
return true;
}
longis 8 bytes on your system?fandn. If one-byte buffers are passed to them, there will be buffer overflow because multi-byte read and written will be performed to them.if (fread(n,sizeof *n,1,f) != 1)is a first improvement. Rest of code should not assume 8 bytes for along. And should not assume a certain endian.&n?