Problem with circular reference and pointers

Problem with circular reference and pointers
0.0 0


Hello guys,

I started using cocos2dx 3 days ago, so I’m a n00b, anyway, I’m following this tutorial

And it makes use of circular reference, so I had a problem with the next part

class HelloWorld …

CCArray* tileDataArray; //no NSMutableArray on cocos2dx so I made use of CCArray

class Unit …

HelloWorld* theGame;


I need to access from the Unit class to the tileDataArray of the HelloWorld class at the moment the ccTouchBegan function is dispatched, and that’s the problem, if I try to read the tileDataArray the application crashes with a *Segmentation fault (core dumped)*

any idea of how to solved it? do I have to change the architecture avoiding this class of circular reference ?




Kinda hard to give a solution with just that amount of code. If I understand correctly, you want to access tileDataArray from the Unit class, is that correct?

What you could do is to:

  1. Declare tileDataArray as public ;
  2. Create a *getTileDataArray()* method on the HelloWorld class ; or
  3. Post more info. It’s really hard to read minds.


Thanks for the quick response.

I have attached the involved classes, it’s an ugly code but I made it in 2 nights and I’m facing the language problem, I’m a java developer, but I want to use c/c++ and cocos2dx so it has been hard to deal with it.

The application fails in the function HelloWorld::getTileData(CCPoint) when it is being called by Unit::markPossibleAction(int).

Thanks in advance,



Since you’re adding the Unit objects to the HelloWorldScene object, you can use getParent* to get the parent layer.
For example:
bool Unit::ccTouchBegan {
if {
return false;
if ) {
return false;
state = kStateGrabbed;
theGame = ( HelloWorldScene * ) this > getParent;
> unselectUnit();

return true;

You can also try having a static **HelloWorldScene** object, but I don’t recommend it.


I think I found the problem. The CCArray::create() method creates an “autorelease” object, due to the circular reference in some moment this object is released, I don’t understand why but that’s the cause of my problem, so I decided to use the alternative form to create those arrays (and in general all the class members that can be set as autorelease)

CCArray * tileDataArray = new CCArray();
…and paying attention to delete/release the object
tileDataArray = NULL;

and now it works !

@Lance Gray Thanks