首页 > 怎么编写段错误(Segmentation fault)的程序

怎么编写段错误(Segmentation fault)的程序

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 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 const int g = 10;
int main()
{int *p = (int *)&g;(*p)++;  /* SEGV: try to modify const var */printf("%d", *p);return 0;
}

3_1 尝试运行在.data section

#include int g = 10; /* .data section, r+w, not x */
typedef void (*F_P)();void f()
{printf("hello zeku
");
}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 尝试运行在stack

#include   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 void f()
{printf("hello zeku
");
}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;
}

扩展:

进程收到SIGSEGV信号后,我们给SIGSEGV注册回调函数,打印backtrace.

refer to: sigaction/backtrace/backtrace_symbols

更多相关:

  •         Apache POI是一个开源的利用Java读写Excel,WORD等微软OLE2组件文档的项目。        我的需求是对Excel的数据进行导入或将数据以Excel的形式导出。先上简单的测试代码:package com.xing.studyTest.poi;import java.io.FileInputSt...

  • 要取得[a,b)的随机整数,使用(rand() % (b-a))+ a; 要取得[a,b]的随机整数,使用(rand() % (b-a+1))+ a; 要取得(a,b]的随机整数,使用(rand() % (b-a))+ a + 1; 通用公式:a + rand() % n;其中的a是起始值,n是整数的范围。 要取得a到b之间的...

  • 利用本征图像分解(Intrinsic Image Decomposition)算法,将图像分解为shading(illumination) image 和 reflectance(albedo) image,计算图像的reflectance image。 Reflectance Image 是指在变化的光照条件下能够维持不变的图像部分...

  • 题目:面试题39. 数组中出现次数超过一半的数字 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。 示例 1: 输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2 限制: 1 <= 数组长度 <= 50000 解题: cl...

  • 题目:二叉搜索树的后序遍历序列 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 参考以下这颗二叉搜索树:      5     /    2   6   /  1   3示例 1: 输入: [1,6,3,2,5] 输出...

  • main函数声明   背景: main函数经常会声明为以下方式: int main(); int main(int argc, char* argv[]); int main(int argc, char* argv[], char*envp[]); 还有些会将返回类型替换为void,最常见的就是 void main();  ...