0
// 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?

4

2 に答える 2

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

sizeof(JPG_KEY) * 4あなたはバイトを読んでいて、アドレス&key以降にそれらを保存しています。key1つに十分なスペースしかないため、sizeof(JPG_KEY)スタック内の他の変数を上書きしています。

freadの署名は次のとおりです。

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

つまり、1つだけを読み取りたい場合は、次のようにJPG_KEY記述します。

fread(&key, sizeof(JPG_KEY), 1, fp);
于 2012-07-20T21:24:08.080 に答える
2

fread(&key, sizeof(JPG_KEY), 4, fp)4 * sizeof(JPG_KEY)もちろん、に格納できる以上のバイトを読み取りますkey4をaに置き換えると1、すべてが機能するはずです。

fread(3)マンページから:

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

関数fread()は、ストリームが指すストリームから、各サイズがバイト長のデータのnmemb要素を読み取り、ptrで指定された場所に格納します。

4つの「jpegキー」を読みたい場合、つまり、JPG_KEY key[4];

変数がジャンプする理由は、オーバーフローによって他の変数がスタックのfread後にある可能性が高いため、これらの変数が上書きされるためです。key

于 2012-07-20T21:24:11.060 に答える