首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么gcc打印“分割故障: 11"?

为什么gcc打印“分割故障: 11"?
EN

Stack Overflow用户
提问于 2019-01-23 22:18:58
回答 1查看 116关注 0票数 2

当我使用gcc编译器运行下面的程序时,我的结果是“分割错误: 11",但当我在"https://www.onlinegdb.com/online_c_compiler”上运行同样的程序时,它执行得非常好。我想知道,为什么gcc会在这里抛出分割错误?

代码语言:javascript
复制
#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

代码语言:javascript
复制
$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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-23 22:53:11

这里的评论是错误的:

代码语言:javascript
复制
myArray y[2]; //equivalant to y[10][2]

y实际上被定义为:

代码语言:javascript
复制
int y[2][10];

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

然后,当您使用从09的行索引i和从01的列索引来访问y[i][j]时,只要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 (以便它与注释匹配):

代码语言:javascript
复制
int y[10][2];
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54329288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档