Note that there are some explanatory texts on larger screens.

plurals
  1. POThis pointer suddenly becomes 0x0 in C++
    primarykey
    data
    text
    <p>I have an (apparently) very simple class initialization, with two constructors, and when I want to create a new Friendship, the this pointer of the first argument has the appropriate pointer value, but the second doesn't. </p> <p>I'll explain better in code - this is one my constructors:</p> <pre><code>Friendship::Friendship(const User &amp;u1, const User &amp;u2){ *user1 = u1; *user2 = u2; } </code></pre> <p>When I do this in my Test class:</p> <pre><code>bool Test::insertFriendship(User *user1, User *user2) { bool friendshipExists = verifyFriendship(user1, user2); if(!friendshipExists) { friendships.push_back(new Friendship(*user1, *user2)); // this is a ptr_vector container return true; } return false; } </code></pre> <p>It gives me a EXC_BAD_ACCESS error at the push_back line because apparently the 'this' pointer of the user1 WORKS when it gets to the constructor and it points to a valid memory address, but when it goes to do the user2, the 'this' pointer of user2 points to 0x0 and it fails because that's basically trying to re-deference NULL when it gets to the operator = overload.</p> <p>Ex: when it tries to create a new Friendship:</p> <p>this->user1's mem address = 0x100100b20 this->user2's mem address = 0x0 - error!</p> <p>while </p> <p>u1's mem address = 0x7fff5fbff900 u2's mem address = 0x7fff5fbff898</p> <p>I mean, these u1 and u2 mem addresses are valid so why the heck doesn't it work when I try to do:</p> <pre><code>*user1 = u1; //works cos this is 0x100100b20 *user2 = u2; // fails cos this is 0x0 even though u2 is a valid mem address! </code></pre> <p>Anyone know why this strange behavior? Even if I switch user1 and user2 in my push_back, it still won't work at the SECOND one. It's always that pesky second one that never works.</p> <p>Ah, this is my Friendship header file, nothing too complex.</p> <pre><code>#include "User.h" #ifndef Friendship_h #define Friendship_h class Friendship { friend class Test; protected: User *user1; User *user2; public: Friendship(const User &amp;u1, const User &amp;u2); Friendship(const Friendship &amp;a); ~Friendship(); }; #endif </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload