首页 > 解决方案 > 为什么 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

标签: cgcc

解决方案


这里的评论是错误的:

myArray y[2]; //equivalant to y[10][2]

y实际上定义为:

int y[2][10];

IE。y有 2 行,每行 10 个int

然后,当您使用范围从 toy[i][j]的行索引和i0to 的9列索引j进行0访问时,只要(or ) 大于或等于(or ) 1,您最终都会越界访问数组。i * ROW_SIZE + ji * 10 + jROW_SIZE * ROW_CNT10 * 2

例如,y[9][1]尝试访问第 10 行的第二个值。但是 中只有 2 行y

试图越界访问数组具有未定义的行为未定义的行为意味着任何事情都可能发生,包括看起来运行良好或崩溃。

要修复您的代码,请定义y如下(使其与注释匹配):

int y[10][2];

推荐阅读