斗士狗 2010-02-27 09:23 采纳率: 0%
浏览 385
已采纳

什么是内存区段错误?

What is a segmentation fault? Is it different in C and C++? How are segmentation faults and dangling pointers related?

转载于:https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault

  • 写回答

12条回答 默认 最新

  • 叼花硬汉 2010-02-27 09:36
    关注

    Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs. Whenever you get a segfault you know you are doing something wrong with memory – accessing variable that has already been freed, writing to a read-only portion of the memory, etc. Segmentation fault is essentially the same in most languages that let you mess with the memory management, there is no principial difference between segfaults in C and C++.

    There are many ways to get a segfault, at least in the lower-level languages such as C(++). A common way to get a segfault is to dereference a null pointer:

    int *p = NULL;
    *p = 1;
    

    Another segfault happens when you try to write to a portion of memory that was marked as read-only:

    char *str = "Foo"; // Compiler marks the constant string as read-only
    *str = 'b'; // Which means this is illegal and results in a segfault
    

    Dangling pointer points to a thing that does not exist any more, like here:

    char *p = NULL;
    {
        char c;
        p = &c;
    }
    // Now p is dangling
    

    The pointer p dangles because it points to character variable c that ceased to exist after the block ended. And when you try to dereference dangling pointer (like *p='A'), you would probably get a segfault.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 怎么获取下面的: glove_word2id.json和 glove_numpy.npy 这两个文件
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug