怎么编写段错误(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 <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 尝试运行在.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 尝试运行在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;
}

扩展:

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

refer to: sigaction/backtrace/backtrace_symbols

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值