栈内存问题

栈内存问题排查: 

编译时增加-g 和安全编译选项-fstack-protector

-g:生成调试信息,用于后续gdb调试;

-fstack-protector:在编译时会在函数栈框中插入一个canary,并实现了通过这个canary来检测函数栈是否被破坏;如果程序执行过程中出现越界执行到canary随机数,程序会立马结束;

makefile如下:

target = stack_1
$(target):stack_1.c
	#gcc -g $^ -o $@ -lpthread
	#gcc -Wall -O2 -g $^ -o $@ -lpthread
	gcc -fstack-protector -Wall -O2 -g $^ -o $@ -lpthread
clean:
	rm -rf $(target)

stack_over.c 如下: 

#include <stdio.h>
#include <string.h>
#include <pthread.h>

#if 0
/*栈越界,编译时使用-fstack-protector,程序执行时遇到越界会立马结束*/
void test_func(int a)
{
	char p[10] = {0};
	strcpy(p,"1234567890abcdef");
	printf("p:%s\n",p);
	
}
#else
/*栈溢出,通过LR指针确认*/
void test_func(int a)
{
	char p[20480*2] = {0};
	strcpy(p,"1234567890abcdef");
	printf("p:%s\n",p);
	
}
#endif

void *thread_test_stack(void *param)
{
	printf("thread_test_stack start...\n");
	
	test_func(2);
	
	printf("thread_test_stack end...\n");
	return NULL;
}

int main(void)
{
	pthread_t thread_id;
	int ret ,stacksize = 20480; /*thread 堆栈设置为20K,stacksize以字节为单位。*/

	pthread_attr_t attr;
	ret = pthread_attr_init(&attr); /*初始化线程属性*/
	if (ret != 0)
	  return -1;
  
	ret = pthread_attr_setstacksize(&attr, stacksize);
	if(ret != 0)
	  return -1;
	  
	ret = pthread_create(&thread_id, &attr, thread_test_stack, NULL);
	if(ret != 0)
	  return -1;
  
	pause();
	  
	ret = pthread_attr_destroy(&attr); /*不再使用线程属性,将其销毁*/
	if(ret != 0)
		return -1;
	
}

 

编码建议:

1.不要申请大的局部变量

2.开辟合适大小的线程栈空间

3.函数入参尽量指针传递

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值