我在这段代码中遇到了分割错误,在该部分中,我scanf
表示电路板的值。一开始,我扫描了两次以获取尺寸。
#include <stdio.h>
#include <stdlib.h>
#include "maxsum.h"
int main() {
int x,y,n,m,**board;
scanf("%d %d",&n,&m);
board=malloc(n*sizeof(int));
if (board==NULL) {
printf("Unable to allocate memory \n");
return 1;
}
for (x=0;x<n;x++) {
*(board+x)=malloc(m*sizeof(int));
if (*(board+x)==NULL) {
printf("Unable to allocate memory \n");
return 1;
}
}
for (x=0;x<n;x++) {
for (y=0;y<m;y++) {
scanf("%d",&board[x][y]); // the error happens in this line ,and only when variable x is about to become n-1 when n>4 (very confused as to why)//
}
}
printf("%d \n",Solve(n,m,board)); //not relevant //
return 0;
}
您分配的内存量不足:
board=malloc(n*sizeof(int));
您正在将board
设置为int *
的数组,但是您只是为int
的数组分配空间。 int
最有可能比系统上的int *
小,因此分配的空间不足。随后,您在分配的内存末尾写入,结果为undefined behavior。
将此分配更改为:
board=malloc(n*sizeof(int *));
或更妙的是:
board=malloc(n*sizeof(*board));