user1664463
user1664463

Reputation: 1

EXEC_BAD_ACCESS happening with xcode when using pointers

I am just learning the basics of c++, and have gotten to the section about pointers. However, I am getting an error when trying to assign a value to the contents of the pointer. Any tips?

#include <iostream>
class X
{
public:
    int * x;
    X()
    {
        int * x = new int;
    }   
};

int main (int argc, const char * argv[])
{

    X test;
    *(test.x) = 10;
    return 0;
}

Upvotes: 0

Views: 78

Answers (1)

freestyler
freestyler

Reputation: 5444

This line:

int * x = new int;

declare a local variable x. The public member x is still not initialized to point to any allocated memory.

So change it to :

x = new int;

will work.

Upvotes: 2

Related Questions