返回语句中的分段错误

时间:2014-10-25 11:36:49

标签: c++ segmentation-fault return malloc

我使用tmx解析器来解析文件,我有一个名为map1的2D数组,
如果我声明它是静态的,int map1[w][h]程序运行正常 但是在声明它是动态的(通过malloc& 2D指针)时,我得到了分段错误:

int main()
{
    Tmx::Map map;
    int width,height; 
    map.ParseFile("new.tmx");
    if (map.HasError())
    {
        cerr<<"Error loading map:"<< map.GetErrorText();
        return 1;
    }
    const Tmx::Layer* current_layer = map.GetLayer(0); 
    width = current_layer->GetWidth();;
    height = current_layer->GetHeight();
    cout<<"\n\n"; 

//    int map1[height][width];          
    int **map1;
    map1=(int**)malloc(height*sizeof(int*));
    for(int i=0;i<width;i++)
        map1[i]=(int*)malloc(width*sizeof(int));

    for (int i = 0; i < width; i++)
        for (int j = 0; j < height; j++)
            map1[j][i] = current_layer->GetTileId(i, j);

    for(int i=0;i<height;i++)
    {
        for(int j=0;j<width;j++)
        {     
            cout.width(3);
            cout<< map1[i][j]<<" "; 
        }
        cout<<"\n";
    } 
    return 0;
}

我试图通过gdb调试,我知道“return语句”是错误的原因,

(gdb) backtrace
#0  malloc_consolidate (av=0xb7e83420 <main_arena>) at malloc.c:4151
#1  0xb7d4bbab in _int_free (av=0xb7e83420 <main_arena>, p=<optimized out>, have_lock=0) at malloc.c:4057
#2  0xb7eed9df in operator delete(void*) () from /usr/lib/i386-linux-gnu/libstdc++.so.6
#3  0xb7eeda2b in operator delete[](void*) () from /usr/lib/i386-linux-gnu/libstdc++.so.6
#4  0xb7fcf0eb in Tmx::Layer::~Layer() () from /home/user/Documents/TMX/tmxparser-master/build/libtmxparser.so.1
#5  0xb7fc9b3f in Tmx::Map::~Map() () from /home/user/Documents/TMX/tmxparser-master/build/libtmxparser.so.1
#6  0x08048d4a in main () at main.cpp:69
(gdb) frame 6
#6  0x08048d4a in main () at main.cpp:69 
69      return 0;

1 个答案:

答案 0 :(得分:1)

第一个循环应该迭代到height,而不是width