Home > Software design >  Illegal hardware instruction on a c program compiled on Mac
Illegal hardware instruction on a c program compiled on Mac

Time:12-18

I am getting an illegal hardware instruction error when compiled on mac. Appreciate any pointers.

#include<iostream>
using namespace std;
  
int * fun(int * x)
{
    return  x;
}
int main()
{
    int * x;
    *x=10;
    cout << fun(x);
    return 0;
}

CodePudding user response:

Pointers are just pointers. In your code there is no integer that you could assign a value to.

This

int * x;

Declares x to be a pointer to int. It is uninitialized. It does not point anywhere. In the next line:

*x=10;

You are saying: Go to the memory that x points to and assign a 10 to that int. See the problem? There is no int where x points to, because x doesnt point anywhere. Your code has undefined behavior. Output could be anything.

If you want to assign 10 to an int you need an int first. For example:

#include<iostream>
using namespace std;
  
int * fun(int * x)
{
    return  x;
}
int main()
{
    int y = 0;
    int * x = &y;
    *x=10;
    cout << fun(x);
    return 0;
}

This assigns 10 to y. The cout is still printing the value of x, which is the adress of y. It does not print the value of y. Not sure what you actually wanted.

CodePudding user response:

The problem is that in your program the pointer x is not pointing to any int variable. So first you have to make sure that the pointer x points to an int object as shown below.

You can sovle this as shown below:

    int i = 0;       //create the int object to which x will point 
    int *x = &i;     //make x point to variable i
    *x = 10;         //dereference the pointer x and assign 10 to the underlying variable i
    cout << *fun(x); //this prints 10
  •  Tags:  
  • c
  • Related