Question

I am having issues with my insertion function causing segmentation fault(core dump). I honestly have no clue what that error exactly means.

Here is my insertion function:

void insert(Iterator<E> itr, E data)
{
  Node<E>* newnodeptr = new Node<E>();
  newnodeptr -> data = data;
  newnodeptr -> next = itr.current;
  itr.current -> prev -> next = newnodeptr;
  newnodeptr -> prev = itr.current -> prev;
  itr.current -> prev = newnodeptr;
}

The code I am testing this function on is this.

list<record> testlist;

name = "susan";
grade = 10;
temprec.studname = name;
temprec.Grade = grade;

testlist.push_back(temprec);

name = "joe";
grade = 15;
temprec.studname = name;
temprec.Grade = grade;

testlist.push_front(temprec);

name = "kerry";
grade = 7;
temprec.studname = name;
temprec.Grade = grade;

testlist.push_back(temprec);

searchit = testlist.begin();
for(searchit = testlist.begin(); searchit != testlist.end(); searchit++)        
  {
    cout << (*searchit).Grade << endl;
  }

searchit = studentlist.begin();
searchit++;
searchit++;

name = "frank";
grade = 11;
temprec.studname = name;
temprec.Grade = grade;

testlist.insert(searchit , temprec);
for(searchit = testlist.begin(); searchit != testlist.end(); searchit++)        
  {
    cout << (*searchit).Grade << endl;
  }

My error occurs after the first display so I believe the insertion function is the cause. Please help me understand what I am doing wrong here and how to fix it.

No correct solution

OTHER TIPS

Your searchIt is working on the studentlist list, but everything else is working on testlist. Unless there is some other code that is adding to studentlist, it will probably be empty, so searchit++ will go past the end. In any event, it will be adding to studentlist and so won't show up in your output

searchit = studentlist.begin();

Segmentation-Fault usually means that you try to access some part of the memory that is not under the control of or is a restricted region of your program. Such things happen when you try to access invalid pointers or dereference iterators outside the container bounds.

Since you say it yourself, that you can display the content of testlist, I'm going stick to the same advice Dark gave you: You probably haven't inserted anything into studentlist before acessing it. The dec/inc operators of iterators have to be able to access the storage element of the container to find the next one in general. If the iterator is invalid it will likely access memory locations out of range.

Or does your program crash in the first for loop?

Secondly, why are you inserting so complicated? You do not need to take care of the prev/next handling of the list. That's what these container classes are for: To abstract away the detail. If you want better memory allocation you would specify a separate allocator for that purpose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top