c - 为什么我会遇到段错误(二进制数据解析)c

标签 c segmentation-fault

我一次扫描 512 个字节的原始位。如果前 4 个字节与 jpeg 文件后缀匹配,我将创建一个新的 jpeg 并将该 block 以及所有后续 block 写入其中,直到遇到新的 jpeg 后缀。

由于某种原因,它在第一个写入调用之后的读取调用上出现段错误。

/** * 恢复.c * * 计算机科学 50 * 问题集 4 * * 从取证图像中恢复 JPEG。 */

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

typedef uint8_t  BYTE;

int main(int argc, char* argv[])
{
    //load in file
    FILE* file = fopen("card.raw", "r");
    FILE* newfile = NULL;

    //error opening file
    if (file==NULL){
        return 1;
    }

    //create buffer and outfile index
    BYTE buffer[512]; //
    int filecount = 0;
    char newfilename[3];

    //iterate through file, break on eof
    while (1){//(!feof(file)){//(fgetc(file) != EOF){

        //seek back to 512 block start
        //fseek(file,-1,SEEK_CUR);
        //fread(&buffer,1,512,file);
        if (fread(buffer,512,1,file) <= 0){
            break;
        }

        //Check if first 4 bytes are jpeg signature
        if ((buffer[0] == 0xff &&
             buffer[1] == 0xd8 &&
             buffer[2] == 0xff &&
             buffer[3] == 0xe0)||
            (buffer[0] == 0xff &&
             buffer[1] == 0xd8 &&
             buffer[2] == 0xff &&
             buffer[3] == 0xe1 )){

            //close out previously created jpeg
            if (newfile != NULL){
                //file close error
                if (fclose(newfile) == EOF){
                    return 2;
                }
                newfile = NULL;
            }

            //create new jpeg
            sprintf(newfilename,"%03d.jpeg",filecount++);
            newfile = fopen(newfilename,"w");

        }

        //Write blocks to newfile
        if (newfile != NULL){
            if (fwrite(buffer,512,1,newfile) <= 0){
                return 4;
            }

        }
    }

    //close out last newfile 
    if (newfile != NULL){
        //file close error
        if (fclose(newfile) == EOF){
            return 3;
        }
        newfile = NULL;
    }

    //close infile
    fclose(file);



//we should find 16 images


}

最佳答案

没有足够的数组来容纳文件名

char newfilename[3];

当你这样做的时候

sprintf(newfilename,"%03d.jpeg",filecount++);

这需要

char newfilename[9];

关于c - 为什么我会遇到段错误(二进制数据解析)c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29723962/

相关文章:

c - 在 C 中伪造寄存器读取

c++ - 在 Qt MainWindow 上设置 WA_DeleteOnClose 属性时,程序在删除 ui 指针时崩溃

在 C 中编译和运行没有 main() 的程序

c - 双链表显示函数中的段错误

c - 有什么方法可以保证段错误吗?

c - 非常基本的加密

c - Xcode可以跳转到c站lib的#define

python - 段错误 - Python -> C

c - 将 isdigit 与 if 一起使用

c - 在 C 中写入 Linux sysfs 节点