【问题标题】:Can someone explain why this gets a seg fault (C programming)?有人可以解释为什么会出现段错误(C 编程)吗?
【发布时间】:2012-10-26 09:08:11
【问题描述】:
int load_byte(int memory[],int address) {
//This function works by finding the appropriate word then masking
//to obtain the relevant byte
int index,section;

    switch (address>>28) {
        case 0:
            index = address - START_ADDRESS;
            printf("index = %d",index);
        case 1:
            index = address - START_DATA_ADDRESS;
        case 7:
            index = address - START_STACK_ADDRESS;
   }

    section = index%4;
    index = index/4;
    switch (section) {
    case 0:
        return memory[index]&0x000000ff;
    case 1:
        return (memory[index]&0x0000ff00)>>8;
    case 2:
        return (memory[index]&0x00ff0000)>>16;
    case 3:
        return (memory[index]&0xff000000)>>24;
    }

}

START_ADDRESS 的值为 0x00400000,我使用的示例地址为 0x00400002,只是这个函数一直给我一个 seg 错误,不太明白为什么,因为有问题的数组的大小为 1000。提前致谢.

【问题讨论】:

  • 可能是因为数组大小不足或访问越界?尝试调试你的程序
  • 如果您尝试访问 null,通常会发生分段错误
  • 一个不同的错误:>> 在像int 这样的签名类型上通常会在最高位为 1 时移动 1 位。这种行为取决于实现,但我知道大多数实现以这种方式工作。如果发生,这将导致地址 >= 0x80000000 出现问题。
  • 顺便提一下,在第一个switch 的情况下不要使用break;。控件可能会到达其他情况。
  • Desolator 知道了,非常感谢T_T,对于愚蠢的错误感到抱歉

标签: c segmentation-fault


【解决方案1】:

您的第一个开关看起来很奇怪,只处理了 0、1 和 7。并且每个案例的末尾都没有break; 语句。

【讨论】:

    【解决方案2】:

    代码:

    switch (address>>28) {
        case 0:
            index = address - START_ADDRESS;
            printf("index = %d",index);
        case 1:
            index = address - START_DATA_ADDRESS;
        case 7:
            index = address - START_STACK_ADDRESS;
        }
    

    由于address0x00400002,所以switch将从case 0开始执行, 并且每个case X 中都没有break,所有代码都将运行。也就是说,最后index 将等于address - START_STACK_ADDRESS

    也许这就是原因。

    尝试在cases 之间添加breaks。

    switch (address>>28) {
        case 0:
            index = address - START_ADDRESS;
            printf("index = %d",index);
            break;
        case 1:
            index = address - START_DATA_ADDRESS;
            break;
        case 7:
            index = address - START_STACK_ADDRESS;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2014-12-13
      • 1970-01-01
      • 2021-08-04
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多