【问题标题】:Segmentation fault (core dumped) if index iterates in reverse如果索引反向迭代,则出现分段错误(核心转储)
【发布时间】:2012-06-28 15:50:53
【问题描述】:

我有一段非常简单的代码,它从文件中读取字符。如果索引y 从低到高迭代,一切正常。但是,如果它从高到低迭代(注释行),它会给我 seg 错误问题。有人可以解释为什么会这样吗?谢谢!

void read_ct_from_file( unsigned char** ct, const size_t row, const size_t column, FILE* inf ) {
    size_t x, y;
    for( x = 0; x < row; x++ ) {
        for( y = 0; y < column; y++ ) { 
        //for( y = column - 1; y >= 0; y-- ) { // iterate from high to low

              fscanf( inf, "%02x", &ct[x][y] );
              printf( "%02x ", ct[x][y] );
        }
        printf( "\n" );
    }
}

【问题讨论】:

    标签: c arrays segmentation-fault coredump


    【解决方案1】:

    size_t 是无符号的,所以你的循环将在y = 0 之后继续max_unsigned,即 >= 0。

    【讨论】:

    • 我不太明白你的解释,能不能详细点?那么循环会在 y = 0 之后继续吗?它会变成 y = -1?
    • 不,不是-1; size_t 是一个无符号整数,因此永远不会是负数。 y=0后,y为2^32-1
    • 要想看懂Stefan的评论,必须看懂overflow。使用无符号整数,小于 0 时会溢出。
    • @Stefan,我现在明白了,循环索引在最后一次迭代中超出了界限。谢谢!
    • @RustyTheBoyRobot,我现在明白了。谢谢!
    【解决方案2】:

    顺便说一句,让 unsigned size_t 索引 避免环绕下溢的好方法是这种构造:

    void read_ct_from_file( unsigned char** ct, const size_t row, const size_t column, FILE* inf ) {
        size_t x, y;
        for( x = 0; x < row; x++ ) {
            for ( y = column; y-- > 0; ) { // iterate from high to low
    
                  fscanf( inf, "%02x", &ct[x][y] );
                  printf( "%02x ", ct[x][y] );
            }
            printf( "\n" );
        }
    }
    

    【讨论】:

    • 我已经接受了一个答案。但是非常感谢您提供的新提示!
    【解决方案3】:
    for( y = column - 1; y > 0; y-- ) { // iterate from high to low
    

    试试这个。

    【讨论】:

    • 索引 y 为 0 时呢?这是数组中的最后一个元素。
    • 它们可能是指for (y = column; y &gt; 0; y--) ...,然后在任何地方都使用y - 1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多