当我使用 gcc 编译器运行下面的程序时,我最终出现“段错误:11”,但是当我在“https://www.onlinegdb.com/online_c_compiler”处运行相同的程序时,它执行得非常好。我想知道,为什么 gcc 会在这里抛出段错误?
#include <stdio.h>
int main(){
typedef int myArray[10];
myArray x = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};//Equivalant to x[10]
myArray y[2]; //equivalant to y[10][2]
int counter = 0;
for(int i = 0; i < 10; i++){
for(int j = 0; j < 2; j++){
//printf("%i %i\n", i, j);
y[i][j] = counter++;
}
}
printf("\n\nElements in array x are\n");
for(int i = 0; i < 10; i++){
printf("x[%i] = %i\n", i, x[i]);
}
printf("\n\nElements in array y are\n");
for(int i = 0; i < 10; i++){
for(int j = 0; j < 2; j++){
printf("y[%i][%i] = %i\t", i, j, y[i][j]);
}
printf("\n");
}
return 0;
}
我使用的是 gcc 版本 4.2.1。操作系统:MAC
$gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.0 (clang-1000.10.44.4)
Target: x86_64-apple-darwin18.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
最佳答案
这里的评论是错误的:
myArray y[2]; //equivalant to y[10][2]
y
实际上定义为:
int y[2][10];
即。 y
有 2 行,每行 10 int
每个。
当您访问y[i][j]
时行索引 i
范围从 0
至9
和列索引 j
来自0
至1
,当 i * ROW_SIZE + j
时,您最终会越界访问数组。 (或 i * 10 + j
)大于或等于 ROW_SIZE * ROW_CNT
(或10 * 2
)。
例如,y[9][1]
尝试访问第 10 行的第二个值。但 y
中只有 2 行.
Trying to access an array out of bounds has undefined behavior 。 Undefined behavior意味着任何事情都可能发生,包括看起来运行良好或崩溃。
要修复您的代码,请定义 y
如下(因此与评论相符):
int y[10][2];
关于c - 为什么 gcc 打印 "Segmentation fault: 11"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54329288/