Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lparstat: reversed arguments to fread() in get_name() #67

Open
nathanlynch opened this issue Jul 1, 2021 · 2 comments
Open

lparstat: reversed arguments to fread() in get_name() #67

nathanlynch opened this issue Jul 1, 2021 · 2 comments

Comments

@nathanlynch
Copy link
Contributor

void get_name(const char *file, char *buf)
{
	FILE *f;
	char tmpbuf[64];
	int rc;

	f = fopen(file, "r");
	if(!f) {
		sprintf(buf, "%c", '\0');
		return;
	}
	rc = fread(tmpbuf, 64, 1, f);
	fclose(f);

	if (!rc)
		sprintf(buf, "%s", tmpbuf);
}

The fread() as used here does a partial read of a single element for any stream that yields less than 64 bytes, and the value of a partial element is unspecified according to https://pubs.opengroup.org/onlinepubs/009695399/functions/fread.html

@tyreld
Copy link
Member

tyreld commented Jan 27, 2022

I find it funny that the example of fread in the provided reference is basically identical to what get_name does, and they store the return value as bytes_read even though that would only be the case if the size and nmemb values were reveresed.

EXAMPLES

Reading from a Stream

The following example reads a single element from the fp stream into the array pointed to by buf.

#include <stdio.h>
...
size_t bytes_read;
char buf[100];
FILE *fp;
...
bytes_read = fread(buf, sizeof(buf), 1, fp);
...

@tyreld
Copy link
Member

tyreld commented Jan 27, 2022

Another interesting note is that the code seems to actually rely on a partial read where fread returns zero.

rc = fread(tmpbuf, 64, 1, f);
fclose(f);

if (!rc)
	sprintf(buf, "%s", tmpbuf);

If fread actually managed to read a full 64bytes then rc == 1 and we don't execute sprintf.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants