0

我在从字符串输入创建 tmx 映射时遇到问题。

bool LevelManager::initLevel(int currentLevel)
{
    const char* 映射;
    尝试 {

        地图 = LevelManager::getLevel(currentLevel);
    } 捕捉(整数){
        投掷1;
    }
    如果(地图!= NULL){
        CCLog("%s", 地图);
        tileMap = CCTMXTiledMap::create(map);
        tileMap->setAnchorPoint(ccp(0,0));
        tileMap->setPosition(ccp(15,20));
        this->addChild(tileMap, 5);
        backgoundLayer = tileMap->layerNamed("Background");
    } 别的 {
        投掷1;
    }
    返回真;
}

那是我的代码。它非常不稳定。大多数时候它会崩溃,有时它不会。我正在从字符串地图加载我的地​​图。Wich 是一个 const *char。我的地图被命名为 Level1.tmx,当我像这样加载地图时: tileMap = CCTMXTiledMap::create("Level1.tmx"); 它总是有效,从不崩溃。而且我知道 map 的值是 Level1.tmx 因为我在加载之前将它记录在行中。

当它崩溃时,日志输出如下: (lldb) 和 tileMap->setAnchorPoint(ccp(0,0)); 它说“线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x0)

有谁知道为什么会发生这种情况以及如何解决它?

非常感谢。

ps:我用的是xcode,最新的cocos2d-x版本和iPhone模拟器

编辑:

使用断点,我检查了加载 tilemap 时出现问题的地方。

就行 tileMap = CCTMXTiledMap::create(map); 我的变量映射仍然很好

但在线 tileMap->setAnchorPoint(ccp(0,0)); 它突然损坏(大部分时间)

4

2 回答 2

1

It sounds like you're returning a char* string created on the stack, which means the memory may or may not be corrupted, depending on circumstances, moon phases, and what not.

So the question is: How is getLevel defined and what does it do (post the code)?

If you do something like this:

const char* LevelManager::getLevel(int level)
{
    char* levelName = "default.tmx";
    return levelName;
}

…then that's going to be the culprit. The levelName variable is created on the stack, no memory (on the heap) is allocated for it. The levelName variable and the memory it points to become invalid as soon as the method returns.

Hence when the method leaves this area of memory where levelName points to can be allocated by other parts of the program or other method's stack memory. Whatever is in that area of memory may still be the string, or it may be (partially) overridden by other bits and bytes.

PS: Your exception handling code is …. well it shows a lack of understanding what exception handling does, how to use it and especially when. I hope these are just remnants of trying to get to the bottom of the issue, otherwise get rid of it. I recommend reading a tutorial and introductions on C++ exception handling if you want to continue to use exceptions. Especially something like (map != NULL) should be an assertion, not an exception.

于 2013-01-17T19:28:35.407 回答
0

我修好了它。

const char* 是罪魁祸首。

将我的地图作为 char * 返回时,它完美无缺。

    const char *levelFileName = level.attribute("file").value();
    char *levelChar = new char[strlen(levelFileName) + 1];
    std:: strcpy (levelChar, levelFileName);

return levelChar;

这就是我现在返回地图的方式。

于 2013-01-17T20:54:22.467 回答