【问题标题】:How do I locate the source of a segmentation fault? (CS50: recover.c)如何定位分段错误的根源? (CS50:恢复.c)
【发布时间】:2015-03-28 12:45:20
【问题描述】:

我正在尝试为 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);
}

(对不起,冗长的溢出行!)

【问题讨论】:

  • 使用像GDB这样的调试器。或者,您也可以在这里和那里使用printf 语句来了解seg-fault发生的位置。
  • 那我是不是每隔一段时间就放一个printf,看看哪里不打印?
  • 我将标题更改为“char title[5]”,但由于“title[5]”不是 char*,出现了很多错误。
  • free(buffer); 也是错误的。删除这个。
  • 我也意识到我忘了在名字后面放一个.jpg。

标签: c segmentation-fault cs50


【解决方案1】:

在这一行(和其他)

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

没有分配给title的内存,它被声明了

char *title;

仅此而已。

char title[BLOCK];

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

unsigned char buffer[BLOCK];

另外,你需要另一个

found+=1;

else 代码块中打开img 之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-02
    • 2021-01-29
    • 2020-12-09
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2020-12-28
    相关资源
    最近更新 更多