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?
The problem is that you're typecasting a char*
to an int*
and then dereferencing p
which leads to undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.
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.