简体   繁体   中英

Why do my int variable values suddenly jump?

// a cursor variable, for positioning purposes
int cursor = 0;

// declare a counter
int counter = 0;

// start a loop
while (counter <= 0)
{
    // get the cursor positioned correctly
    fseek(fp, cursor, SEEK_SET);

    // read the file and search for the jpeg key
    JPG_KEY key;
    fread(&key, sizeof(JPG_KEY), 4, fp);

    // check the key to see if you are at the start of a jpeg
    if( check_jpg_key(key) )
        counter++;

    cursor++;
}

For some reason, my "cursor" and "counter" variables a jumping to ridiculously high ints in the middle of this program instead of incrementing by 1 on each loop. With gdb, I found that the value for cursor jumps from 0 to 2099202 and the value for counter jumps from 0 to 3419700 at this line: fread(&key, sizeof(JPG_KEY), 4, fp);

Why?

fread(&key, sizeof(JPG_KEY), 4, fp);

You are reading sizeof(JPG_KEY) * 4 bytes, storing them from address &key onwards. Since key has only enough space for one sizeof(JPG_KEY) , you are overwriting other variables in the stack.

fread 's signature is:

size_t fread(void *ptr, size_t  size,  size_t  nitems,  FILE *stream);

That is, if you want to read only 1 JPG_KEY , you should write:

fread(&key, sizeof(JPG_KEY), 1, fp);

fread(&key, sizeof(JPG_KEY), 4, fp) reads 4 * sizeof(JPG_KEY) bytes which if of course more than you can store in key . Replace the 4 with a 1 and everything should work.

From the fread(3) manpage :

 size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); 

The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.

Your code would be correct if you wanted to read four "jpeg keys", ie if you had JPG_KEY key[4];

The reason why your variables jump around is that the overflow causes your fread call to overwrite those other variables since they are most likely located after key on the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM