簡體   English   中英

為什么運行程序時出現“ Segmentation Fault”錯誤?

[英]Why am I getting “Segmentation Fault” when I run my program?

我的程序對由隨機像素覆蓋的圖像進行解碼,要對圖像進行解碼,我必須將每個像素的紅色分量乘以10。綠色和藍色分量與新的紅色分量的值相同。 我創建了多個輔助函數,以使代碼在main中更易於閱讀,但是當我嘗試運行a.out時,會不斷收到“ Segmentation Fault”。 我似乎找不到我的錯誤! 感謝幫助。

void check_argument(int arg_list)
{
   if (arg_list < 2)
   {
      perror("usage: a.out <input file>\n");
   }
}

void print_pixel(int a, FILE *out)
{
   int r, g, b;

   r = a * 10;

   if (r > 255)
   {
      r = 255;
   }

   g = r;
   b = r;

   fprintf(out, "%d\n", r);
   fprintf(out, "%d\n", g);
   fprintf(out, "%d\n", b);
}

void read_header(FILE *in)
{
   char str[20];

   for (int i = 0; i < 3; i++)
   {
      fgets(str, 20, in);
   }
}

FILE*  open_files(FILE *infile, char *input[])
{
   infile = fopen(input[1], "r");

   if (infile == NULL)
   {
      perror("Error: Cannot read file.\n");
   }

   return infile;
}

void decode(int arg_list, char *in[])
{
   FILE *input, *output;

   int check, red, green, blue;

   open_files(input, in);
   output = fopen("hidden.ppm", "w");

   fprintf(output, "P3\n");
   fprintf(output, "%d %d\n", 500, 375);
   fprintf(output, "255\n");

   read_header(input);
   check = fscanf(input, "%d %d %d", &red, &green, &blue);

   while (check != EOF)
   {
      print_pixel(red, output);
      check = fscanf(input, "%d %d %d", &red, &green, &blue);
   }

   fclose(input);
   fclose(output);
}

int main(int argc, char *argv[])
{
   check_argument(argc);
   decode(argc, argv);
}

由於這應該是家庭作業,因此我將嘗試向您展示一些常見的bug來源以及如何查找它們。

  1. 在此之前,必須(應該)將使用的變量分配給它。 這對於指針尤其重要,例如FILE *

  2. 如果一個函數(例如fopen() )失敗,它通常通過返回一個特殊值來表示這一點,在繼續之前必須檢查該值。

  3. 要檢查變量具有哪個值,可以使用printf()來顯示它。

這是為了查找主要錯誤,例如段錯誤。

但是,邏輯錯誤也很難找到:如果讀取3個值並將它們存儲到變量中,則全部使用它們而不是僅使用其中一個可能會更有用。 (但也許這不是此練習的目標。)


在了解到這不是在給定程序中搜索錯誤的任務,而是自己編寫程序之前,我先寫了幾行,所以現在我將更加具體。

FILE *fopen()返回的東西。 您可以返回它,也可以將其寫入變量或指針“更深一層”間接指向的另一個存儲位置。

因此,您應該重寫open_files() (順便說一句:為什么file * s *?它目前只有一個...):

用於返回值(首選):

FILE* open_files(char *input[])
{
   FILE *infile = fopen(input[1], "r");

   if (infile == NULL)
   {
      perror("Error: Cannot read file.\n");
   }

   return infile;
}

並用

input = open_files(input);

或“通過引用傳遞”:

void open_files(FILE **infile, char *input[])
{
   *infile = fopen(input[1], "r");

   if (*infile == NULL)
   {
      perror("Error: Cannot read file.\n");
   }

   return *infile;
}

並用

open_files(&input, in);

只有這樣做,您才能真正在調用者的站點上input變量input

調用open_files(input, in); 您將在input沒有文件句柄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM