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.
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 examplemalloc()
will callabort()
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.