Search code examples
c++ciphonexcodecocos2d-iphone

Memory Related Crash : 3 Dimensional Array in Cocos2d Game


Here is Code:

Declaration in .h

@interface LevelManager : NSObject{

}
@property int ***construtorDeMundo;

Initialisation and malloc

-(id)init {
    self = [super init];
    if(self != nil){
        construtorDeMundo = (int***) malloc ( NUMFASES * sizeof(int *));

        for (int i = 0; i < NUMFASES ; i++) {
            construtorDeMundo[i] = (int**) malloc (MAX_PONTOS_CRITICOS * sizeof(int));
        }

        for (int i = 0; i < NUMFASES; i++)
            for (int j = 0; j < MAX_PONTOS_CRITICOS; j++) {
                construtorDeMundo[i][j] = (int*) malloc (PROPRIEDADES * sizeof(int));
                for (int k = 0; k < PROPRIEDADES ; k++)
                    construtorDeMundo[i][j][k] = 0;
            }

        [self pegaInformacoes];
    }
    return self;
}

Code to access:

 for (int j = 1; j < [elements count]; j++) {
            if(j <= PROPRIEDADES+1){
                NSString *valor = (NSString *)[elements objectAtIndex:j];
                construtorDeMundo[fase][i][j-1] = [((NSNumber*)valor) intValue];
            }
        }

Game randomly crashes for different index in last function. Something related to malloc...How to fix ? Please help me if you know.

Sorry this game code is not in English...not written by me.

Thanks in advance.


Solution

  • Finally Fixed problem. In above code, wrong value provided for sizeof().

    Here is updated code:

    -(id)init {
        self = [super init];
        if(self != nil){
            construtorDeMundo = (int***) malloc ( (NUMFASES) * sizeof(*construtorDeMundo));
    
            for (int i=0; i < NUMFASES; ++i)
                construtorDeMundo[i] = NULL;
    
            for (int i = 0; i < NUMFASES ; ++i) {
                construtorDeMundo[i] = (int**) malloc (MAX_PONTOS_CRITICOS * sizeof(*construtorDeMundo[i]));
            }
    
            for (int i=0; i < NUMFASES; ++i)
                for (int j=0; j < MAX_PONTOS_CRITICOS; ++j)
                    construtorDeMundo[i][j] = NULL;
    
            for (int i = 0; i < NUMFASES; ++i)
                for (int j = 0; j < MAX_PONTOS_CRITICOS; ++j) {
                    construtorDeMundo[i][j] = (int*) malloc ((PROPRIEDADES) * sizeof(*construtorDeMundo[i][j]));
                    for (int k = 0; k < PROPRIEDADES ; k++)
                        construtorDeMundo[i][j][k] = 0;
                }
    
    
            [self pegaInformacoes];
        }
        return self;
    }