Program received signal SIGABRT, Aborted
Asked Answered
E

1

7

There is a structure in my program

struct List      
{
    int data;
    List *next;
};

and a function of adding an element to the tail of the list:

void addL(List* &tail, int dat)   
{

    if (tail==NULL) 
    {
        tail = new List;
        tail->data = dat; 
        tail->next=NULL;
    }   
    else
    {
        tail->next = new List;
        tail = tail->next;
        tail->data = dat;
        tail->next = NULL;
    }
}

gdb says about the problem

terminate called after throwing an instance of 'St9bad_alloc'
  what():  std::bad_alloc

Program received signal SIGABRT, Aborted.
0xb7fdd424 in __kernel_vsyscall ()

in line

tail->next = new List;

I tried to make another variable of type List like that:

List* add;
add = new List;

but got the same problem in second line.

How to rewrite this correctly? And is it any need to paste here the function which calls addL? Sorry, if this question had already been asked, I could not understand while looking through them.

Ectoblast answered 5/4, 2015 at 17:13 Comment(1)
We have no idea what you're doing wrong from this. Where is your testcase?Hinda
S
5

Either you are out of memory (maybe your list is too big for your memory) or you are trying somewhere in the memory that you are not allowed to.


Since the list is small, then I suspect this is the issue (as stated here):

abort() is usually called by library functions which detect an internal error or some seriously broken constraint. For example malloc() will call abort() if its internal structures are damaged by a heap overflow.

Another relevant question lies here.

So I suggest you take a piece of paper and a pen and draw what your code does. There is probably a tangling pointer or something.

Sabra answered 5/4, 2015 at 17:15 Comment(3)
There is a small list (of 8 elements)Ectoblast
Edited @Tami. Seems you have a memory error there! Your function looks OK to me. Nice question btw, +1.Sabra
Thank you, I'll really overlook all the code once more, cause there are really lots of pointers, where an error may occurEctoblast

© 2022 - 2024 — McMap. All rights reserved.