簡體   English   中英

C - 將結構寫入二維數組會導致分段錯誤

[英]C - Writing a struct into a 2D array causes Segmentation Fault

我正在嘗試編寫一個程序,將文本文件讀入二維結構數組,但嘗試將結構放入該數組會導致程序崩潰。

這是程序

ppm.c

#include "ppm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

image parse_ascii_image(FILE *fp) {
  char magic[3];
  char comm[1024];
  char size[10];
  image img;
  int height;
  int width;

  ... // some code
  
  pixel **pixelarr;
  printf("Commencing internal malloc...\n");
  if (height <= 1024 && width <= 1024 && height > 0 && width > 0){
    pixelarr = (pixel **) malloc(height * sizeof(pixel*));
  }else{
    fprintf(stderr, "Error: Invalid image size: %d * %d", width, height);
    return img;
  }
  for (int i = 0; i < height; i++){
    pixelarr[i] = malloc(width * sizeof(pixel));
    
  }

  int d = 0;
  int e;
  printf("Filling in array:\n");

  for (int row = 0; row < height; row++){
    for (int col = 0; col < width; col++){
      for (int i = 0; i < 3; i++){
        while ((e = fgetc(fp)) != '\n'){
          d = d * 10;
          e = e - 60;
          d += e;
        }
        if (i == 0){
          pixelarr[row][col].red = d;
        }
        if (i == 1){
          pixelarr[row][col].green = d;
        }
        if (i == 2){
          pixelarr[row][col].blue = d;
        }
        d = 0;
      }      
    }
  }
  printf("Finished! Copying pixels over: \n");
  for (int row = 0; row < height; row++){
    for (int col = 0; col < width; col++){
      img.pixels[row][col] = pixelarr[row][col];
    // ^^^This is where the program crashes
    }
  }
  printf("Finished! Freeing internal malloc:\n");
  
  ... // some more code

}

來自 ppm.h 的相關信息:

#ifndef PPM_H
#define PPM_H 1

#include <stdio.h>

...

typedef struct pixel pixel;
struct pixel {
  int red;
  int green;
  int blue;
};

typedef struct image image;
struct image {
  enum ppm_magic magic; // PPM format
  char comments[1024];  // All comments truncated to 1023 characters
  int width;            // image width
  int height;           // image height
  int max_color;        // maximum color value
  pixel **pixels;       // 2D array of pixel structs.
};

...

// Parses an ASCII PPM file.
image parse_ascii_image(FILE *fp);

...

#endif

如果有人可以幫助我找出導致我的程序在那里崩潰的原因,我將不勝感激。 謝謝!

幾個問題:
1 : img.pixels 從未初始化。 每當您創建指向某事物的指針而不先為其分配值時,請嘗試將其設置為 NULL 以便更容易調試。 請注意,這不會解決問題。 要修復它,只需使用結構實例初始化它們。
2 :你應該釋放pixelarr 大多數現代操作系統都會這樣做,但這仍然是非常非常好的做法。
3 :不使用嵌套循環會更容易,而是使用img.pixels = pixelarr嗎? 它實現了相同的效果(除非這是針對 class 的,並且這部分是必需的)。

暫無
暫無

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

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