C sprintf导致未定义的行为

C sprintf导致未定义的行为,c,printf,C,Printf,问题在评论中 由于sprintf函数,出现了一些未定义的情况。 加上缓冲区[0]=0xff语句必须放在fopen命令之后,否则会发生错误。我也不知道为什么会这样。有人能指出什么地方不对劲吗 #include <stdio.h> #include <stdint.h> //unsinged int of size 1 byte typedef uint8_t BYTE; int main() { // open memory card file FI

问题在评论中

由于sprintf函数,出现了一些未定义的情况。 加上缓冲区[0]=0xff语句必须放在fopen命令之后,否则会发生错误。我也不知道为什么会这样。有人能指出什么地方不对劲吗

#include <stdio.h>
#include <stdint.h>

//unsinged int of size 1 byte
typedef uint8_t  BYTE;

int main() {

    // open memory card file
    FILE* memcard = fopen("card.raw","r");

    BYTE buffer [512];
    char name [7];
    int n = 0;

    // open a file to store the initial garbage in card.raw
    FILE*file = fopen("useless.txt","w");

    // read blocks from card.raw till fread doesnt read anything
    while(fread(buffer, 1, 512, memcard)!= 0) {

        //check the first four bytes for jpeg signature
        if((buffer[0] == 0xff) &&(buffer[1] == 0xd8) && (buffer[2] == 0xff) && ((buffer[3] == 0xe0) || (buffer[3] == 0xe1))) { 
            fclose(file);

            printf("%x b\n", buffer[0]);
            //output is "ff b" 
            sprintf(name,"%03d.jpg",n);
            printf("%x a\n", buffer[0]);
            //output is "0 a"

            // somehow the sprintf function changes the value of buffer[0] 

            file = fopen(name,"w"); 

            //buffer[0] = 0xff which reassing 0x ff to buffer[0] has to come after the fopen command, otherwise this happens
            //001.jpg  (invalid encoding), but the value of buffer[0] remains the same 0xff
            buffer[0] = 0xff;
            n++;

            printf("%x \n", buffer[0]);     
        }       

        //write 512 bytes into the open file
        fwrite(buffer, 1, 512, file);    
    }

    fclose(file);

    if(feof(memcard))
        printf("End of file\n");

    fclose(memcard);
}
#包括
#包括
//大小为1字节的非单精度整数
typedef uint8_t字节;
int main(){
//打开存储卡文件
FILE*memcard=fopen(“card.raw”、“r”);
字节缓冲区[512];
字符名[7];
int n=0;
//打开一个文件,将初始垃圾存储在card.raw中
FILE*FILE=fopen(“无用的.txt”、“w”);
//从card.raw读取块,直到fread不读取任何内容
而(fread(缓冲区,1512,内存卡)!=0){
//检查jpeg签名的前四个字节
如果((缓冲区[0]==0xff)&&(缓冲区[1]==0xd8)&(缓冲区[2]==0xff)&((缓冲区[3]==0xe0)| |(缓冲区[3]==0xe1)){
fclose(文件);
printf(“%x b\n”,缓冲区[0]);
//输出为“ff b”
sprintf(名称,“%03d.jpg”,n);
printf(“%x a\n”,缓冲区[0]);
//输出为“0 a”
//sprintf函数以某种方式更改了缓冲区[0]的值
文件=fopen(名称,“w”);
//buffer[0]=0xff,必须在fopen命令之后重新分配0x ff到buffer[0],否则会发生这种情况
//001.jpg(无效编码),但缓冲区[0]的值保持不变0xff
缓冲区[0]=0xff;
n++;
printf(“%x\n”,缓冲区[0]);
}       
//将512字节写入打开的文件
fwrite(缓冲区,1512,文件);
}
fclose(文件);
if(feof(记忆卡))
printf(“文件结束\n”);
fclose(memcard);
}

字符名[7]
不够大,无法容纳
%03d.jpg\0“


sprintf(名称,“%03d.jpg”,n)
之后发生的一切都是偶然的。

您正遭受典型缓冲区溢出的灾难性事件。您声明了
char name[7]
,但存储“%03d.jpg”只需要8个字节。
sprintf
函数会自动将
NULL
\0
)字节追加到字符串的末尾。小心

123.jpg\0

非常感谢你。现在我把名字的长度改为8,一切又恢复正常了。