怎么编写段错误(Segmentation fault)的程序
生活随笔
收集整理的這篇文章主要介紹了
怎么编写段错误(Segmentation fault)的程序
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
On Unix-like operating systems, a process that accesses invalid memory receives the SIGSEGV signal. On Microsoft Windows, a process that accesses invalid memory receives the STATUS_ACCESS_VIOLATION exception.
1.最常見的SEGV: 訪問0地址
#include <stdio.h>int main()
{int *p = 0;printf("%d", *p); /* SEGV: try to access address 0 */return 0;
}
2.修改const 變量
int main(void)
{char *s ="hello zeku"; /* s in .rodata section */*s ='o'; /* SEGV: write .radata section */return 0;
}
#include <stdio.h>const int g = 10;
int main()
{int *p = (int *)&g;(*p)++; /* SEGV: try to modify const var */printf("%d", *p);return 0;
}
3_1?嘗試運(yùn)行在.data section
#include <stdio.h>int g = 10; /* .data section, r+w, not x */
typedef void (*F_P)();void f()
{printf("hello zeku\n");
}int main()
{F_P fp = f;fp();F_P fp1 = (F_P)&g;fp1(); /* SEGV: try to execute in .data section */return 0;
}
?3_2 嘗試運(yùn)行在stack
#include <stdio.h> typedef void (*F_P)();int main (void)
{ int m = 5; /* stack: rw, not x*/int n = 6;F_P fp = (F_P)&m;fp(); /*SEGV: excute in stack */return 0;
}
4. 修改代碼段
#include <stdio.h>void f()
{printf("hello zeku\n");
}int main()
{int *p = (int *)&f;(*p)++; /*SEGV: try to write .text section*/return 0;
}
5. 棧溢出
int main(void)
{main(); /* SEGV: stack overflow */return 0;
}
擴(kuò)展:
進(jìn)程收到SIGSEGV信號后,我們給SIGSEGV注冊回調(diào)函數(shù),打印backtrace.
refer to:?sigaction/backtrace/backtrace_symbols
總結(jié)
以上是生活随笔為你收集整理的怎么编写段错误(Segmentation fault)的程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求冻字开头的成语接龙!
- 下一篇: 求一个王者荣耀QQ个性签名。