-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

newTableですNULL

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++;
    }

または、コードを単純化するために、イテレータは常にインクリメントされるため、ループ内の1つの場所でインクリメントするだけです(の各ブランチでif\else)。

于 2012-12-07T17:34:36.143 に答える