sprintf导致未定义的行为

时间:2014-07-28 20:16:16

标签: c printf

问题在评论中。

因为sprintf函数而发生了一些未定义的事情。 另外,必须在fopen命令之后放置buffer [0] = 0xff语句,否则会发生错误。我也不知道为什么会这样。谁能指出什么错了?

#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);
}

2 个答案:

答案 0 :(得分:3)

char name[7]不足以容纳"%03d.jpg\0"

sprintf(name,"%03d.jpg",n)之后发生的一切都是偶然的。

答案 1 :(得分:2)

您正遭遇经典缓冲区溢出的灾难性事件。您声明了char name[7],但您需要正好8个字节来存储&#34;%03d.jpg&#34;。 sprintf函数会自动将NULL\0)字节附加到字符串的末尾。要小心!

123.jpg\0