The below method causes a segmentation fault. The method is intended to insert something into some position of a linked list. It works as long as the first if statement is true. If not, it gives a segmentation fault, even though I threw an exception in the else case. What is going on?
void hello::addbeforeIth(int I, el_t newNum)
{
int i;
i = 0;
if (!(I<1||I>Count+1))
{
if (isEmpty()||I==Count+1)
{
addRear(newNum);//References rear
return;
}
if (I == 1)
{
addFront(newNum);
return;
}
else
{
Node *p;
Node *q;
p = Front;
q = Front;
while (i<I)
{
p = p->Next;
i++;
}
i = 0;
while (i<(I-1))
{
q = q->Next;
i++;
}
Node *r;
r = new Node;
r->Elem = newNum;
q->Next = r;
r->Next = p;//qrp
Count++;//Count line
}
}
else{throw OutOfRange();}
}
EDIT: It throws the exception unless you do it in a try block. I'm doing this:
try
{
l.addbeforeIth(9,12);
}
catch (hello::OutOfRange)
{cerr << "Error has occurred: out of range"; }
If there's an error, we're not going to exit; we'll just move on.
Yeah okay I forgot to declare p. That didn't cause problems yet as I didn't call it. But I will call it later so thanks. The incorrect catch block is the problem right now.
if (!(I<1||I>Count+1))
{
...}
else{throw OutOfRange();}
Run case 2. Uncomment these lines. Add the try to the top of the block. It was in the original program but I accidentally missed copying it when I pasted from emacs.
This code is in casetwo
try
{
//l.addbeforeIth(9,12);
}
catch (hello::OutOfRange)
{cerr << "Error has occurred: out of range"; }
try
{
//l.addbeforeIth(0,0);
}
catch (hello::OutOfRange)
{cerr << "Error has occurred: out of range"; }