c - 如何定位段错误的根源? (CS50 : recover.c)

标签 c segmentation-fault cs50

我正在尝试为 CS50 编写一个 C 语言程序,从 .raw 文件中恢复 JPG(一次读取 512 个字节并查看它是否以 JPG 内容开头),但它始终出现段错误。我如何知道问题的根源是什么?多谢你们! (这是我的代码供引用)

      /**
 * recover.c
 *
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 */

 //0xff 0xd8 0xff 0xe0
 //0xff 0xd8 0xff 0xe1

#define BLOCK 512
#define START1END 0xe0
#define START2END 0xe1

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

//making variables
int found = 0; 
char* title;
FILE* img;
int ifopen = 1;

int main(int argc, char* argv[])
{
    //opening file
    FILE* inptr = fopen("card.raw", "r");
    //checking if file opening failed
    if (inptr == NULL)
    {
        return 2;
    }
    //sets the begins or jpgs
    uint8_t checkjpg1[4] = {0xff, 0xd8, 0xff, 0xe0};
    uint8_t checkjpg2[4] = {0xff, 0xd8, 0xff, 0xe1};

    //making buffer
    unsigned char buffer[512];

    //going through the file
    while(fread(&buffer,sizeof(char),BLOCK,inptr) == BLOCK)
    {
         //checking if begin == the possible begin of jpg    
         if ((buffer[0] == checkjpg1[0] && buffer[1] == checkjpg1[1] && buffer[2] == checkjpg1[2]) && 
         (buffer[3] == checkjpg1[3] || buffer[3] == checkjpg2[3]))
         {
            //if a jpg is not open
            if (ifopen == 1)
            {
                //make one
                found+=1;
                sprintf(title,"00%d",found);
                img = fopen(title,"a");
            }
            else//else
            {
                //end the one and open new one
                fclose(img);
                sprintf(title,"00%d",found);
                img = fopen(title,"a");
            }
         }
         else if(img != NULL)
         {
             fwrite(buffer,sizeof(char),BLOCK,img);
         }
    }

    fclose(inptr);
    free(buffer);
}

(抱歉,线路太长了!)

最佳答案

在这一行(和其他行)

sprintf(title,"00%d",found);

没有内存分配给title,已声明

char *title;

但仅此而已。

char title[BLOCK];

会更好。顺便说一句,在声明 buffer 时,您不使用 BLOCK ,它应该是

unsigned char buffer[BLOCK];

此外,您还需要另一个

found+=1;

else 代码块中打开 img 之前。

关于c - 如何定位段错误的根源? (CS50 : recover.c),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29317315/

相关文章:

c++ - 带有段错误的 Valgrind 泄漏检测

c - 漏洞利用:SIGSEGV、段错误

c - Unload() 递归 C Segfault(类似 TRIE 的数据库) CS50 pset5

c++ - 在这种情况下,GCC 等现代编译器会执行尾例优化吗?

需要 Cooja 技术信息

C:在列表上使用哨兵

python - 在 Docker 中使用 Tesserocr 时出现段错误

c - 将数据插入到 trie 中

C中的计数排序段错误

c - Free() 语句崩溃?帮助这个函数解决:(