斗士狗 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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应