I would like to understand why I am getting a bus error with this code.
int main()
{
int p=34;
int *pp= (int *) ((char *)&p+1);
cout<<*pp<<"\n";
return 0;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It will no doubt be an alignment issue. On many architectures, certain types have to be aligned properly, an example being that 4-byte integers must start on a 4-byte boundary.
If you access non-aligned data, some architectures won’t care, others will run slower, still others (such as in this case) will fall in a screaming heap.
When you create the integer
p, it will be aligned correctly on the stack at an address which is a correct multiple.By moving that address up on byte, and de-referencing that as an
int, you’re causing theSIGBUS.This link at Oracle shows the alignment requirements. In short: