Error 0xC0000005 with a simple code wtf?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class ImOk{
   public:
   int x,y;
};
class Dude{
    public:
    ImOk* t;
    Dude(ImOk &T){
        cout<<"Ok";
        *t = T;
        cout<<"NotOk";
    }
};
ImOk mk;
int main(){
   Dude dude(mk);
   return 0;
}

And then I get the error:
1
2
Process returned -1073741819 (0xC0000005)   execution time : 14.521 s
Press any key to continue.

Also, only "Ok" is printed, but not "NotOk".

So. what's wrong???????


I use Code::Blocks IDE.
ImOk* t;
t is an uninitialised pointer. It could contain any random address.

Therefore *t = T; this assignment is updating the memory location pointed to by that same pointer. This is the cause of the error.

You could fix this by putting
t = new ImOk;
before attempting to use the pointer.

If you do so, there should be a corresponding delete t; in the destructor of class Dude.

Alternatively, you could put t = &T; instead of *t = T;
In this case, the pointer t instead of pointing to its own independent object, is pointing to the parameter T, which in turn represents the object named mk.

Last edited on
Really... you don't need (and shouldn't use) pointers here at all. Just change 't' to be an object instead of a pointer.

1
2
3
4
5
6
7
8
class Dude{
    public:
    ImOk t;  // <- no need for a pointer
    Dude(ImOk &T){
        cout<<"Ok";
        t = T;  // <- this is fine
        cout<<"NotOk";
    }
Alright I understand now. just changed to t=&T; and it's fine now. thanks :)

I had to use pointers because I wanted to change passed ImOk directly.
tnx again.
Topic archived. No new replies allowed.