什么是堆栈粉碎(C)? [英] what is stack smashing (C)?

查看:253
本文介绍了什么是堆栈粉碎(C)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

int str_join(char *a,  const char *b) {
   int sz =0; 
   while(*a++) sz++;  
   char *st = a -1, c;  
   *st = (char) 32;
   while((c = *b++)) *++st = c;  
   *++st = 0;
   return sz;
}

....

char a[] = "StringA"; 
printf("string-1 length = %d, String a = %s\n", str_join(&a[0],"StringB"), a);

输出:

string-1的长度= 7,char * a = StringA StringB

string-1 length = 7, char *a = StringA StringB

***检测到堆栈粉碎****:/T02已终止

*** stack smashing detected **** : /T02 terminated

已中止(核心已弃用)

我不明白为什么它显示 stack smashing ?什么是*堆栈粉碎?还是我的编译器错误?

I don't understand why it's showing stack smashing? and what is *stack smashing? Or is it my compiler's error?

推荐答案

嗯,堆栈粉碎堆栈缓冲区溢出是一个相当详细的主题,您将在这里进行讨论.可以参考此Wiki文章以获取更多信息.

Well, stack smashing or stack buffer overflow is a rather detailed topic to be discussed here, you can refer to this wiki article for more info.

来到这里显示的代码,问题在于,数组a的大小不足以容纳最终的并置结果.

Coming to the code shown here, the problem is, your array a is not large enough to hold the final concatenated result.

因此,通过说

 while((c = *b++)) *++st = c;

您实际上访问的是绑定内存不足,该内存会调用未定义行为.这是您遇到堆栈粉碎"问题的原因,因为您正在尝试访问不属于您的进程的内存.

you're essentially accessing out of bound memory which invokes undefined behavior. This is the reason you're getting the "stack smashing" issue because you're trying to access memory which does not belong to your process.

要解决此问题,您需要确保数组a包含足够的空间,以将第一个和第二个 string 串联在一起.简而言之,您必须提供更大的目标数组.

To solve this, you need to make sure that array a contains enough space to hold both the first and second string concatenated together. You have to provide a larger destination array, in short.

这篇关于什么是堆栈粉碎(C)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆