i am trying to insert a 2 integer values into the linked list, but the program keeps crashing after it gets to inserting into a linked list.

struct termNode
{
       int coeff;
       int exp;
       termNode * link;
};

void insertHead(int c, int e, termNode * & P)
{
     termNode * temp;
     temp -> coeff = c;
     temp -> exp = e;
     temp -> link = NULL;
     
     P -> link = temp;
     P = P -> link;
}

i know the problem is with the inserting as i have done error checking and crashes at this point.

Perhaps it could be because temp is pointing to some random location? Pointers aren't magic, you're responsible for making sure they point somewhere sensible. Since this is C++, I'd also use a constructor to simplify code using termNode:

struct termNode {
  int coeff;
  int exp;
  termNode *link;

  termNode(int coeff, int exp, termNode *link)
    : coeff(coeff), exp(exp), link(link)
  {}
};

void insertHead(int c, int e, termNode*& P)
{
  P->link = new termNode(c, e, NULL);
  P = P->link;
}

Now for the logic of insertHead. You didn't specify how your list is designed, but as it is, insertHead does not insert a new head node. Rather, it inserts a new tail node after P (because the new node's link is NULL rather than P or P->link). If P is the head pointer, you've destroyed your list. The correct logic for inserting a new head is as follows, assuming P is the head pointer:

void insertHead(int c, int e, termNode*& P)
{
  P = new termNode(c, e, P);
}

This preserves the list by assigning it as the new node's link, then P is reset to point to the new node (which is now the new head).

Edited 6 Years Ago by Narue: n/a

Hi, your are declare pointer here

tremNode *temp

But you are forgot to allocate memory for your pointer

tremNode *temp = (tremNode*)malloc(sizeof(struct tremNode));

Careful with pointers...

>Careful with pointers...
Be careful with malloc too. In C++ it's risky because malloc does not call constructors like new or new[]. In general it's recommended to avoid malloc because of this, even for POD types (to remain consistent).

Adding to narue's post the c++ alternative of malloc is using allocators which can be found in the <memory> header.

Allocators allow you to get a chunk of memory without calling any constructors, Check this link: Allocators You can then when you require it construct objects in this space, its a bit involved and puts you in control of the memory management. examples of such a time you might want to do this is when implimenting the stl vector, string or llist types yourself.

If you dont need to do this then using new is probibally the best idea.

hope this helps somewhat

Edited 6 Years Ago by Kanoisa: n/a

This article has been dead for over six months. Start a new discussion instead.