-1

我有这个用于填充表格的代码,但我不断收到分段错误。我无计可施,试图找出错误可能是什么。我的函数接受 2 个映射并遍历它们以查找公共字符串。它将这些公共字符串的 int 值放入一个表中,以计算出现公共字符串的次数。

myMap findTable(mapGraph * dbgraph1, mapGraph * dbgraph2)
{
typedef mapGraph::const_iterator iter;
typedef myMap::const_iterator mapiter;

iter it1 = dbgraph1->begin();
iter it2 = dbgraph2->begin();
int count =0;
myMap * newTable = NULL;

//iterating through the 2 samples of dbgraphs
while (it1 != dbgraph1->end() && it2 != dbgraph2->end())
{
    //a match is found for 2 strings
    if (it1->first == it2->first)
    {
        //the component ids of first sample
        int compdb1 = it1->second->comp;

        //the component ids of second sample
        int compdb2 = it2->second->comp;

        //inserting the component ids and counts in the map
        newTable->insert(make_pair(make_pair(compdb1, compdb2), count));
        count++;

        for (mapiter it = newTable->begin(); it != newTable->end(); it++)
        {
            printf("%i %i\t %i\n", it->first.first, it->first.second, it->second);
        }

        it1++;
        it2++;

    }

    //match not found
    else
        it1++;
        it2++;

}
printf("\nCLEAR\n");
return newTable;
}

这是错误:

Address 0x10 is not stack'd, malloc'd or (recently) free'd
Invalid read of size 8
Process terminating with default action of signal 11 (SIGSEGV)
Access not within mapped region at address 0x10
4

1 回答 1

1

newTableNULL

myMap * newTable = NULL;

并且之前从未分配给有效对象:

newTable->insert(make_pair(make_pair(compdb1, compdb2), count));

取消引用NULL指针是未定义的行为。要么myMap为 动态分配一个实例newTable

myMap* newTable = new myMap(); // Remember to delete later.

或使用堆栈分配的实例:

myMap newTable;

这是一个错误:

//match not found
    else
        it1++;
        it2++;

导致在it2循环的每次迭代中递增,并将导致在迭代器++上被调用。end()改成:

//match not found
    else
    {
        it1++;
        it2++;
    }

或者为了简化代码,只需在循环中的一个位置递增迭代器,因为它们总是递增(在 的每个分支中if\else)。

于 2012-12-07T17:34:36.143 回答