0
int main(void) {

当我尝试初始化两个“PGMImage”类型的结构时,我的问题就在这里。我的错误显示“Main.exe 已停止工作”

    PGMImage img, rotateimg;
    getPGMfile("mandrill.pgm", &img);
    printf("width: %d, height: %d", img.width, img.height);


    return 0;
}

这是 PGMImage:

typedef struct {unsigned char red;
                  unsigned char green;
                  unsigned char blue;
                 }RGB_INT;

struct PGMstructure
  {
    int maxVal;
    int width;
    int height;
    RGB_INT data[MAX][MAX];
};

typedef struct PGMstructure PGMImage;
4

1 回答 1

1

事实上,在默认情况下,Windows 上为程序分配的堆栈的默认大小似乎是 1MB。

但是,对于您的程序,当您这样做时PGMImage img,您分配的方式太多了。

解释 :

#define MAX 800 // Find it in your link

typedef struct {unsigned char red;
                  unsigned char green;
                  unsigned char blue;
                 }RGB_INT;

struct PGMstructure
  {
    int maxVal;
    int width;
    int height;
    RGB_INT data[MAX][MAX];
};

typedef struct PGMstructure PGMImage;

所以当你这样做时PGMImage img,你分配了4 个字节+ 4 个字节+ 4 个字节+ 800 x 800 x 3个字节。它提供了1 920 012字节,换句话说,几乎是 2 MB。

在 cpp 中:

std::cout << "Sizeof PGMImage : " << sizeof( PGMImage ) << std::endl;

// gives : "Sizeof PGMImage : 1920012

因此,在 Windows 上出现此错误是正常的。

如果你想解决这个错误:

PGMImage* img = (PGMImage*)malloc( sizeof(PGMImage) );

就是这样!堆上的分配解决了这个问题,但不要忘记free最后!

对堆栈限制原因的一个很好的解释:应该在堆栈上分配的变量的大小是否有最大限制?

于 2013-07-16T20:43:58.463 回答