Program crashes when trying to add node to linked list - c++

I wrote this program, and it crashes when I compile. It says the executable has stopped working and Windows is trying to find a solution. I believe the issue is somewhere in this addPage function I wrote to add a node to a linked list, but I'm not sure what is causing the issue.
void initPage(struct page *head, string programName) {
// Assign Properties of the First Node in the Linked List
head->programName = programName;
head->nextPage = NULL;
}
void addPage(struct page *head, string programName) {
// Initialize First Page if Not Initialized
if (head == NULL) {
initPage(head, programName);
return;
}
// Setup the New Page
page *newPage = new page;
newPage->programName = programName;
newPage->nextPage = NULL;
// Set the Pointer to the Beginning of the Linked List
page *current = head;
// While Traversing the Linked List
while(current) {
// If the End of the List is Reached, Append the Page
if (current->nextPage == NULL) {
current->nextPage = newPage;
return;
}
// Grab the Next Page (If not at the End of the Page)
current = current->nextPage;
}
}

This:
if (head == NULL) {
initPage(head, programName);
passes a null to initPage, which then immediately dereferences it. Boom.
Tip: ALWAYS check a pointer for null before using it.
Also, initPage is an incomplete copy of code in addPage. It seems better to always run the code in addPage that creates the new page (i.e., don't call initPage() at all) and then, once you've got a page, test head for null to see if you should just set head to the new page or iterate the list looking for the end.

Related

Selection sort in single linked list without using swap

I have been trying to solve the selection sort in single linked list without using swap nodes. Using a temp list to store nodes and assign the current list with a new one
//my addlastnode function
void AddLastNODE(LIST &mylist, NODE *p)
{
//Check the list is empty or not
if(isEmpty(mylist))
mylist.pHead = mylist.pTail = p;
else
mylist.pTail->pNext = p;
mylist.pTail = p;
}
void selectionSort(LIST &mylist)
{
//Initialize a temp list to store nodes
LIST mylisttemp;
IntList(mylisttemp);
//Create node
NODE *p;
NODE *i;
//Create min node
NODE *min;
//Check if list is empty or has one node
if(mylist.pHead == mylist.pTail)
return;
//Traverse the list till the last node
for(p=mylist.pHead; p->pNext!=NULL && p!=NULL; p = p->pNext)
{
min=p;
for(i=p->pNext; i!=NULL;i=i->pNext)
{
////Find the smallest data in list
if(i->data < min->data)
min=i;
}
////Add the smallest to a new list
AddLastNODE(mylisttemp, min);
}
//Fill the current list to the new list
if(!isEmpty(mylisttemp))
mylist = mylisttemp;
}
Your code does not reduce the list you are selecting nodes from: the selected node should be removed from it. To make that happen, you need a reference to the node before the selected node, so that you can rewire the list to exclude that selected node.
There is also a small issue in your AddLastNODE function: it does not force the tail node to have a null as pNext pointer. This may be a cause of errors when the function is called with a node that still has a non-null pNext pointer. Secondly, the indentation is off around the else block. It does not lead to a bug in this case, but still it is better to avoid the confusion:
void AddLastNODE(LIST &mylist, NODE *p)
{
if(isEmpty(mylist))
mylist.pHead = p;
else
mylist.pTail->pNext = p;
mylist.pTail = p; // indentation!
p->pNext = nullptr; // <--- better safe than sorry!
}
Then to the main algorithm. It is quite tedious to work with a previous node reference when looking for the node with the minimum value. It helps a bit when you temporarily make the input list cyclic:
void selectionSort(LIST &mylist) {
if (mylist.pHead == mylist.pTail) return;
// Make list temporarily cyclic
mylist.pTail->pNext = mylist.pHead;
LIST mytemplist;
IntList(mytemplist);
while (mylist.pHead != mylist.pTail) {
// Select node:
NODE * beforemin = mylist.pTail;
for (NODE * prev = mylist.pHead; prev != mylist.pTail; prev = prev->pNext) {
if (prev->pNext->data < beforemin->pNext->data) {
beforemin = prev;
}
}
NODE * min = beforemin->pNext;
// Extract selected node:
if (min == mylist.pTail) mylist.pTail = beforemin;
if (min == mylist.pHead) mylist.pHead = min->pNext;
beforemin->pNext = min->pNext;
// And insert it:
AddLastNODE(mytemplist, min);
}
// Move last remaining node
AddLastNODE(mytemplist, mylist.pHead);
// Copy back
mylist = mytemplist;
}
As a side note: You might even want to always keep your list cyclic. This will mean some changes in other functions you may have, as there will be no pNext pointers that are null then.

why java AbstractQueuedSynchronizer next link is not atomically set as part of insertion

As Doug Lea point in the [The java.util.concurrent Synchronizer Framework
][1]http://gee.cs.oswego.edu/dl/papers/aqs.pdf that
But because there are no applicable techniques for lock-free atomic insertion of double-linked list nodes using compareAndSet, this link is not atomically set as part of insertion; it is simply assigned.
pred.next = node;
after the insertion. This is reflected in all usages. The next link is treated only as an optimized path. If a node's successor does not appear to exist (or
appears to be cancelled) via its next field, it is always possible to start at the tail of the list and traverse backwards using the pred field to accurately
check if there really is one.
the add node to sync queue code snippet is, copied form AbstractQueuedSynchronizer source code :
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
my question is, in the sourcecode, the next field of a Node class is a volatile object, if compareAndSetTail success, then the next field of t must not be null, why there may be a null situation. the code snippet is:
static final class Node {
//....ignored
volatile Node next;
volatile Node prev;
//.... ignored
}
Also, I don't quite understand hasQueuedPredecessors. If h != t, then h's next filed should not be null, why h.next == null also means hasQueuedPredecessors?
public final boolean hasQueuedPredecessors() {
// The correctness of this depends on head being initialized
// before tail and on head.next being accurate if the current
// thread is first in queue.
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}

Problems creating a copy function for a linked list

In this instance I am creating a queue implemented as a linked list. The queue has a pointer to the front and a pointer to the back.
Whenever I try to run the driver that tests the queue the program crashes shortly after starting an attempt at copying. My previous linked list program also had issues with the copy function, so I am unable to use it as a reliable reference.
The following code is my copy function:
template<class T>
void queue<T>::copy(const queue<T>& original){
QNodeType<T>* current;
QNodeType<T>* addin;
addin = new QNodeType<T>;
current = original.front_;
count=original.count;
if(front_ != NULL){
destroy();
}
if(original.front_==NULL){
front_=NULL;
back_=NULL;
}
else{
front_= new QNodeType<T>;
addin->item=current->item;
front_=addin;
back_=addin;
if(current->next != NULL){
while(current->next != NULL){
addin= new QNodeType<T>;
addin->item=current->item;
addin->next=NULL;
back_->next=addin;
back_=addin;
current=current->next;
}
}
}
}

C++ Linked List Search Error: STATUS_ACCESS_VIOLATION

I am writing a program that adds, deletes, and displays nodes (that are doubly linked) and their components, but whenever I try to retrieve a node and display it's components I get this error:
2 [main] a 4640 exception::handle: Exception: STATUS_ACCESS_VIOLATION
2875 [main] a 4640 open_stackdumpfile: Dumping stack trace to a.exe.stackdump
I have narrowed it down to the search function within my .h file that is supposed to search to see if there is a node within the linked list that account number being searched. The function returns the node that comes before it, or the "previous" node.
Here is my search function:
bool searchListByAcctNum (int searchKey, nodePtr *prevOut)
{
bool found = false;
nodePtr p = headNum;
nodePtr prev = NULL;
while (p != NULL)
{
if (p->acctNum < searchKey)
{
prev = p;
p = p->nextNum;
}
else
{
if (p->acctNum == searchKey)
found = true;
p = NULL;
}
}
*prevOut = prev;
return found;
If anyone could help me at all, I'd appreciate it!
It looks like your list may be corrupted, or the pointer you're passing to receive the previous node is invalid, since that code looks okay. However, it seems to me that it could be written in a much simpler manner:
bool searchListByAcctNum (int searchKey, nodePtr *prevOut) {
/// Start at beginning of list, use pointer variable to hold previous.
nodePtr p = headNum;
*prevOut = = NULL;
// Process entire list, will exit early if need be.
while (p != NULL) {
// If past it, just return false, caller should ignore prevOut.
if (p->acctNum > searchKey)
return false;
// If equal, return true, prevOut holds previous or NULL if found at start.
if (p->acctNum == searchKey) {
return true;
// Save previous and advance to next.
*prevOut = p;
p = p->next;
}
// Reached end of list without finding, caller should ignore prevOut.
return false;
}

C++ Linkedlist simple question

I'm trying to check if an entity exists in a given linkedlist. This is my code:
bool LinkedList::existByID(int ID)
{
//create node to search through the list
Node * helpNode;
//start it at the top of the list
helpNode = head;
if (head == NULL)
{
return false;
}
//while the item has not yet been found
while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL))
{
if (helpNode->data->indicatedEntity->getID() == ID)
{
//return true - the data exists
return true;
}
else
//if the data has not been found, move on
helpNode=helpNode->next;
}
//if the data has not been found and the end of the
//list has been reached, return false - the item does
//not exist
return false;
}
From the line I marked as the "problem line", the part of the if statement
(helpNode->data != NULL)
I get error CXX0017 (symbol "" not found) and error CXX0030 (expression cannot be evaluated).
This code works if there are no entities in the linkedlist - in other words, if the head is null.
The Node constructor looks like this:
LinkedList::Node::Node()
{
next=NULL;
data=NULL;
}
I've also tried it with the line:
(helpNode != NULL)
and Node constructor
LinkedList::Node::Node(){}
All combinations return the same errors. Any suggestions?
Firstly I recommend fixing a few things with your code.
In your loop you check the data member of helpNode before testing to see if helpNode is actually valid. Imagine you are on the last node - and at the end of the while the following executes - now what gets checked at the top?
helpNode=helpNode->next;
Secondly, once you've checked for helpNode, next you should check that data is valid before checking attributes of data, what if data is NULL?
And now think about what your loop is checking, it's checking that getID() != ID, and yet inside the loop you are testing for the ID, getID() == ID? does that make sense?
I recommend that in your loop, you just check that the next node and data exists, and then within the loop check that the ID matches, and return if true.
Well the line
while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL))
might be a problem if data is NULL, because then you would be trying to access NULL->indicatedEntity
further if indicatedEntity is NULL, then you are trying to access NULL->getID()
you can rewrite it to
while (helpNode->data != NULL && helpNode->data->indicatedEntity != NULL && helpNode->data->indicatedEntity->getID() != ID)
which doesnt look nice, but it does ensure your pointers are not null before trying to access them.