【问题标题】:Segmentation Fault on return statementreturn 语句上的分段错误
【发布时间】:2014-10-25 11:36:49
【问题描述】:

我正在使用 tmx 解析器来解析文件,我有一个名为 map1 的二维数组,
如果我将其声明为静态,即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 statement”是错误的原因,

(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;

【问题讨论】:

  • 您需要重新编译,因为“源文件比可执行文件更新”警告。不要在 C++ 中使用 malloc,使用标准容器,例如 std::vector
  • @BasileStarynkevitch 这里涉及二维矩阵,所以为了简单起见,我暂时避免使用向量;你是想说 malloc 是段错误的原因吗?你能在这段代码的上下文中解释更多关于 malloc 的信息吗?
  • 您可能还想使用一维数组,使用arr[i*width+j] 为矩阵元素 (i,j) 添加访问权限
  • to keep stuff simple , i have temporarily avoided vector 这是第一个错误。学习矢量,你会发现事情变得简单多了。

标签: c++ segmentation-fault return malloc


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多