简体   繁体   English

为什么我的int变量值突然跳?

[英]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. 出于某种原因,我的“光标”和“计数器”变量在此程序的中间变量跃迁到高得离谱的整数,而不是在每个循环中加1。 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); 使用gdb时,我发现在此行上,游标的值从0跳到2099202,计数器的值从0跳到3419700: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. 您正在读取sizeof(JPG_KEY) * 4个字节,从地址&key开始存储它们。 Since key has only enough space for one sizeof(JPG_KEY) , you are overwriting other variables in the stack. 由于key仅有一个sizeof(JPG_KEY)足够空间,因此您将覆盖堆栈中的其他变量。

fread 's signature is: fread的签名是:

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: 也就是说,如果您只想读取1 JPG_KEY ,则应输入:

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 . fread(&key, sizeof(JPG_KEY), 4, fp)读取4 * sizeof(JPG_KEY)个字节,这当然可以存储在key Replace the 4 with a 1 and everything should work. 4替换为1然后一切正常。

From the fread(3) manpage : fread(3)联机帮助页中

 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. 函数fread()从stream指向的流中读取每个长度为字节大小的nmemb数据元素,并将它们存储在ptr给定的位置。

Your code would be correct if you wanted to read four "jpeg keys", ie if you had JPG_KEY key[4]; 如果您想读取四个“ jpeg键”,即您有JPG_KEY key[4];则您的代码是正确的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. 变量跳来跳去的原因是,溢出导致fread调用覆盖了其他变量,因为它们很可能位于堆栈中的key之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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