Re: memcmp() checker: memory access errors
- From: "Arthur J. O'Dwyer" <ajonospam@xxxxxxxxxxxxxx>
- Date: Tue, 19 Dec 2006 15:46:27 -0500 (EST)
On Mon, 17 Dec 2006, kolmogolov@xxxxxxxxx wrote:
/*
Hi, I have removed things irrelevant to reproducing the problem.
What's wrong with my code? Thanks in advance for any hint!
1166425362
*/
I see four bugs, two of which /might/ cause your problem. First, you malloc 'data' and never free it; second, and more importantly,
you try to 'fread' out of a file that was opened as text, not binary.
To fix the second bug, use "rb" instead of "r" as the second argument
to 'fopen'. Does the problem go away?
Any time you're dealing with bits and bytes, you should be using
files opened in binary mode, not text mode.
Third, the line
assert ( 1 == fread(data, probe_len, 1, fp) );should probably be changed stylistically to
assert ( probe_len == fread(data, 1, probe_len, fp) );
and /definitely/ needs to be changed to
rc = fread(data, 1, probe_len, fp);
assert(rc == probe_len);
so that it will continue to work when NDEBUG is #defined (e.g., when
you release the product). This is probably the big bug.
Never put anything inside 'assert' that you want to be evaluated.
The same goes for any in-house assertion-checking macros or functions;
it'll make life easier for the programmers who come after you.
-Arthur
#include <stdio.h>[big snip]
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int probe_img(FILE *fp)
{
unsigned char *data;
unsigned char KDF_header[4]={0x01, 0x03, 0x13, 0x5E};
int probe_len = 256;
int type=-1;
data = malloc( probe_len );
assert ( NULL != data );
assert ( 1 == fread(data, probe_len, 1, fp) );
if ( !memcmp(data, KDF_header, 4) )
{
type = 3;
}
return type;
}
int main(void)
{
FILE *fp = fopen("sample.kdf", "r");
assert ( NULL != fp);
printf("type=%d\n", probe_img(fp) );
return 0;
}
/*
$ echo $CHECKEROPTS
.
- Follow-Ups:
- Re: memcmp() checker: memory access errors
- From: kolmogolov@xxxxxxxxx
- Re: memcmp() checker: memory access errors
- References:
- memcmp() checker: memory access errors
- From: kolmogolov@xxxxxxxxx
- memcmp() checker: memory access errors
- Prev by Date: Re: Files & dirs: historical reasons?
- Next by Date: Re: integer overflow in scanf functions
- Previous by thread: Re: memcmp() checker: memory access errors
- Next by thread: Re: memcmp() checker: memory access errors
- Index(es):
Relevant Pages
|