c - 为什么 gcc 打印“分段错误:11”?
问题描述
当我使用 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];
IE。y
有 2 行,每行 10 个int
。
然后,当您使用范围从 toy[i][j]
的行索引和i
从0
to 的9
列索引j
进行0
访问时,只要(or ) 大于或等于(or ) 1
,您最终都会越界访问数组。i * ROW_SIZE + j
i * 10 + j
ROW_SIZE * ROW_CNT
10 * 2
例如,y[9][1]
尝试访问第 10 行的第二个值。但是 中只有 2 行y
。
试图越界访问数组具有未定义的行为。未定义的行为意味着任何事情都可能发生,包括看起来运行良好或崩溃。
要修复您的代码,请定义y
如下(使其与注释匹配):
int y[10][2];
推荐阅读
- r - 使用 geom_line 和 geom_point 更改图例符号“a”
- kubernetes - 无法使用 Helm Push Artifactory 插件将 helm 包存档推送到工件
- flutter - 在网格视图的中心底部显示小部件
- android - Firebase 通知图标 Unity
- sql - 返回关键字之前的光标无限循环
- wordpress - 访问后端的 Wordpress 用户角色不起作用
- docker - 在 docker 容器上运行 Actinia
- angular - Angular9 迁移后未加载环境定义
- macos - 使用 NUnit 编写的单元测试的 Xamarin iOS 移动应用程序的代码覆盖率
- r - r dataTable 保存为 RDS 而不是 jso