I have this code for filling a table but I keep getting a segmentation error. I’m at my wit’s end trying to find what the error could be. My function takes in 2 maps and iterates through them to find the common strings. It takes the int value of these commons strings and puts it in a table to count the number of times there are common strings.
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;
}
This is the error:
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
newTableisNULL:and is never assigned to a valid object before:
Dereferencing a
NULLpointer is undefined behaviour. Either dynamicaly allocate amyMapinstance fornewTable:or use a stack allocated instance:
This is an error:
resulting in
it2being incremented on every iteration of the loop and will result in++being called on anend()iterator. Change to:Or to simplify the code just increment the iterators at one place in the loop as they are incremented always (in each branch of the
if\else).