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?
... so your program is literally overwriting memory that doesn't own...
that's a bit misleading, it does not matter if the program owns that memory or not. In the shown case the program might very well own that memory, but it might be just memory that something else of the program and that part becomes corrupted due to that. – Carapace