nik*_*hev 2 c segmentation-fault multidimensional-array
我在下面列出了代码。如果我定义ARR_SIZE太多(例如 820),则会出现分段错误错误。但是如果ARR_SIZE不是那么大(例如 320),代码就可以工作。
GDB仅在int main().
我认为问题出在二维数组的初始化阶段,但不确定。
#include "stdio.h"
#include "time.h"
#include "stdint.h"
#define ARR_SIZE 820
#define TICK(X) clock_t X = clock()
#define TOCK(X) printf("time %s: %g sec.\n", (#X), (double)(clock() - (X)) / CLOCKS_PER_SEC)
void copyji(int src[ARR_SIZE][ARR_SIZE], int dst[ARR_SIZE][ARR_SIZE]){
int i, j;
for (j = 0; j < ARR_SIZE; j++)
for (i = 0; i < ARR_SIZE; i++)
dst[i][j] = src[i][j];
}
void copyij(int src[ARR_SIZE][ARR_SIZE], int dst[ARR_SIZE][ARR_SIZE]){
int i, j;
for (i = 0; i < ARR_SIZE; i++)
for (j = 0; j < ARR_SIZE; j++)
dst[i][j] = src[i][j];
}
int main(){
int srcArr1[ARR_SIZE][ARR_SIZE];
int srcArr2[ARR_SIZE][ARR_SIZE];
int dstArr1[ARR_SIZE][ARR_SIZE];
int dstArr2[ARR_SIZE][ARR_SIZE];
int i, j;
for (i = 0; i < ARR_SIZE; i++)
for (j = 0; j < ARR_SIZE; j++){
srcArr1[i][j] = i - j;
srcArr2[i][j] = j - i;
}
TICK(TIME_JI);
copyji(srcArr1, dstArr1);
TOCK(TIME_JI);
TICK(TIME_IJ);
copyij(srcArr2, dstArr2);
TOCK(TIME_IJ);
return 1;
}
Run Code Online (Sandbox Code Playgroud)
您之所以会遇到此错误,是因为您的代码会导致大数组(例如 820)的堆栈溢出,而对于较小的数组则不会。您可以使用malloc.
使用 malloc 的示例:
int **srcArr1 = (int **)malloc(ARR_SIZE * sizeof(int *));
for (i=0; i<ARR_SIZE; i++)
srcArr1[i] = (int *)malloc(ARR_SIZE * sizeof(int));
Run Code Online (Sandbox Code Playgroud)
使用 malloc,您使用堆而不是堆栈动态分配内存,因此这不会导致 seg。过错。
另一种解决方法是全局或静态声明您的数组,这也会从堆而不是堆栈分配内存。