c - 为什么 gcc 打印 "Segmentation fault: 11"?

标签 c gcc

当我使用 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范围从 09和列索引 j来自01 ,当 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 behaviorUndefined behavior意味着任何事情都可能发生,包括看起来运行良好或崩溃。

要修复您的代码,请定义 y如下(因此与评论相符):

int y[10][2];

关于c - 为什么 gcc 打印 "Segmentation fault: 11"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54329288/

相关文章:

c - -rdynamic 仅用于选择符号?

c++ - 使用不同于系统默认编译器的编译器运行 CMake

c - 返回部分结构

c - 在Linux PAM模块中检索用户命令

c - 写入文件并使用带循环的 if 语句

c++ - 使用 CMake 强制进行 32 位编译的正确方法

C 编程 - pthread_create() 循环索引作为参数

c - 在 C 中将项目添加到我的哈希表中

c++ - gcc 在链接时找不到对函数 DoIt() 的引用

c++ - 编译 libgdiplus 源代码以创建静态链接库,即 libgdiplus.so