“检测到堆栈粉碎”的原因是什么?
我是编程新手,目前正在研究地址类型转换。我似乎不明白为什么我会得到这个:***检测到堆栈粉碎***:终止中止(核心转储)
当我运行以下代码时?
#include<iostream>
using namespace std;
void updateValue(int *p){
*p = 610 % 255;
}
int main(){
char ch = 'A';
updateValue((int*)&ch);
cout << ch;
}
以下是我对代码的理解:
ch
的地址被类型转换为 int*
并传递到函数 updateValue()
中。现在,在 updateValue()
堆栈内,创建了一个指向 ch
的整数指针 p
。当 p 被取消引用时,它将 ch
解释为 int
并读取 4(或 8)个字节的连续内存而不是 1。因此,'A'(65) 以及一些垃圾值被分配给
610%255
即 20。
但我不明白,哪里出了问题?
I am new to programming and am currently studying about address typecasting. I don't seem to understand why I am getting this : *** stack smashing detected ***: terminated Aborted (core dumped)
when I run the following code??
#include<iostream>
using namespace std;
void updateValue(int *p){
*p = 610 % 255;
}
int main(){
char ch = 'A';
updateValue((int*)&ch);
cout << ch;
}
Here's what I understand about the code:
The address of ch
is typecasted to int*
and passed into the function updateValue()
. Now, inside the updateValue()
stack, an integer pointer p
is created which points to ch
. When p is dereferenced, it interprets ch
as an int
and reads 4(or 8) bytes of contiguous memory instead of 1. So, 'A'
(65) along with some garbage value gets assigned to 610%255
i.e. 20.
But I don't understand, what and where things are going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您间接通过重新解释的
p
并访问错误类型的对象时,程序的行为是未定义的。当您将指向一种类型的指针重新解释为指向不相关类型的指针时,事情就开始出错了。
一些经验法则:
When you indirect through the reinterpreted
p
and access an object of the wrong type, the behaviour of the program is undefined.Things started going wrong when you reinterpreted a pointer to one type as a pointer to an unrelated type.
Some rules of thumb:
问题是您将
char*
类型转换为int*
,然后取消引用p
这会导致未定义的行为。因此,您看到的(也许看到的)输出是未定义行为的结果。正如我所说,不要依赖具有 UB 的程序的输出。该程序可能会崩溃,这发生在您的情况下。
例如,此处程序崩溃,但此处 它不会崩溃。
因此,使程序正确的第一步是删除 UB。 只有那时您才能开始推理程序的输出。
1有关未定义行为的技术上更准确的定义,请参阅 this 其中提到:程序的行为没有任何限制。
The problem is that you're typecasting a
char*
to anint*
and then dereferencingp
which leads to undefined behavior.So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash which happens in your case.
For example, here the program crashes, but here it doesn't crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
在此语句中,
不属于类型为 char 的对象 ch 的内存将被覆盖。也就是说,对象 ch 占用的不是一个字节,而是覆盖了对应于 int 类型对象分配的内存的 4 个字节。
In this statement
the memory that does not belong to the object ch that has the type char is overwritten. That is instead of one byte occupied by the object ch there are overwritten 4 bytes that correspond to the allocated memory for an object of the type int.