Search code examples
c++visual-c++crashcocos2d-x

Crash on write file procedure !closed


I write a procedure tha must to write 2d-array to a file. Here's code:

void Level::loadLevel(){
    int levelmap[15][9];
    FILE *fp = fopen("resources/lvls/loc1.map", "wb");  
    for (int i=0;i<=15;i++){
        for(int j=0;j<=9;j++){
            levelmap[i][j]=i+j;
            }
    }
    char asd[255];

    for (int i=0;i<=15;i++){
        for(int j=0;j<=9;j++){
            char *buffer=itoa(levelmap[i][j],asd,1);
            fwrite(buffer,2,sizeof(buffer),fp);
            };
        };
    fclose(fp);
 }

it's compiling, but on call this function application is crashed. i call it as menu_selector attribute of cocs2d-x menu item. Why is it crashes?

Update: Changed to file streams ad works excellent


Solution

  • char *buffer=itoa(levelmap[i][j],asd,1);
    

    The last param of itoa is base. It should be 10 instead of 1 (see http://www.cplusplus.com/reference/cstdlib/itoa/ )


    void Level::loadLevel(){
        int levelmap[15][9];
        FILE *fp = fopen("resources/lvls/loc1.map", "wb");  
        for (int i=0;i<=15;i++){
            for(int j=0;j<=9;j++){
                levelmap[i][j]=i+j;
                }
        }
    

    If i == 15 and j == 9, you exceed array's boundaries (levelmap[15][9] means levelmap[0..14][0..8])

    Change conditions in loops to i < 15 and j < 9.