Question

Question: I get a Segmentation fault error sometimes when I addElementBack or print. Am I using...

Question: I get a Segmentation fault error sometimes when I addElementBack or print. Am I using pointers correctly and deleting memory properly?

#ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H

#include <cstdlib>
#include <iostream>

using namespace std;

// Node class
class Node {
int data;
Node* next;
Node* prev;

public:
Node();
Node(int);
void SetData(int newData) { data = newData; };
void SetNext(Node* newNext) { next = newNext; };
void SetPrev(Node* newPrev) { prev = newPrev; };
int getData() { return data; };
Node* getNext() { return next; };
Node* getPrev() { return prev; };
};

class DynamicArray
{
Node *head;
int size;
public:
DynamicArray();
DynamicArray(int);
~DynamicArray(); //destructor to free memory
  
void addElementFront(int);
void addElementBack(int);
void insertElement(int, int);
void delementelement(int, int);
void del(int val);
void removeFront();
void removeBack();
  
int sizeArray();
bool contains(int);
  
void print();
  
};

Node::Node()
{

}

Node::Node(int val)
{
data = val;
}

DynamicArray::DynamicArray()
{
head = NULL;
size = 0;
}

DynamicArray::DynamicArray(int s)
{
head = new Node();
  
for(int i = 0; i < s - 1; i++)
{
addElementBack(0);
}
  
size = s;
}

DynamicArray::~DynamicArray()
{
//delete all nodes
  
delete head;
}

/*
* Function that adds the given value to the front of the array
*/
void DynamicArray::addElementFront(int val)
{
if (head == NULL)
{
head = new Node(val);
head->SetNext(NULL);
}
else {
Node *newNode = new Node(val);
newNode->SetNext(head);
head->SetPrev(newNode);
head = newNode;
}
  
size++;
}

/*
* Function that adds the given value to the back of the array
*/
void DynamicArray::addElementBack(int val)
{
if (head == NULL)
{
head = new Node(val);
}
else if (head->getNext() == NULL)
{
Node* newNode = new Node(val);
head->SetNext(newNode);
newNode->SetPrev(head);
}
else {
Node *temp = head->getNext();
  
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
  
Node *newNode = new Node(val);
newNode->SetPrev(temp);
temp->SetNext(newNode);
}
  
size++;
}

/*
* Inserts a value at a given location. If the location in the array is
* filled, it shifts the values from that location on one time.
*/
void DynamicArray::insertElement(int loc, int val)
{
if(loc == 0) //insert at head
{
Node *newNode = new Node(val);
newNode->SetNext(head);
head = newNode;
}
else
{
Node *temp = head;
int step = 0;
  
while (step != loc - 1)
{
temp = temp->getNext();
step++;
}
  
temp->SetNext(new Node(val));
}
  
size++;
}

/*
* Subtracts a given value from an element at a given location. If the
* subtraction results in a negative number, that element is set to zero.
*/
void DynamicArray::delementelement(int loc, int val)
{
if(loc == 0) //delement head
{
head->SetData(head->getData() - val);
}
else
{
Node *temp = head;
int step = 0;
  
while (step != loc)
{
temp = temp->getNext();
step++;
}
  
temp->SetData(temp->getData() - val);
}
}

/*
* Deletes a given value from the array
*/
void DynamicArray::del(int val)
{
if (head == NULL)
{
printf("%s", "error: array is empty");
}
else if (head->getNext() == NULL && head->getData() == val)
{
head = NULL;
size--;
}
else
{
Node *temp = head->getNext();
bool found = false;
  
while (temp != NULL && !found)
{
if(temp->getData() == val)
{
(temp->getPrev())->SetNext(temp->getNext());
(temp->getNext())->SetPrev(temp->getPrev());
found = true;
}
  
temp = temp->getNext();
}
  
delete temp;
  
size--;
}
}

void DynamicArray::removeFront()
{
if (head == NULL)
{
printf("%s", "error: array is empty");
}
else
{
Node *temp = head;
head = head->getNext();
head->SetPrev(NULL);
delete temp;
size--;
}
}

void DynamicArray::removeBack()
{
if (head == NULL)
{
printf("%s", "error: array is empty");
}
else if (head->getNext() == NULL)
{
head = NULL;
size--;
}
else
{
Node *temp = head->getNext();
  
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
  
(temp->getPrev())->SetNext(NULL);
delete temp;
  
size--;
}
}

int DynamicArray::sizeArray()
{
return size;
}

void DynamicArray::print()
{
Node *temp = head;
  
do {
printf("%d", temp->getData());
temp = temp->getNext();
} while(temp != NULL);
  
printf("%s", "\n");
}

bool DynamicArray::contains(int val)
{
if (head == NULL)
{
return false;
}
else
{
Node *temp = head;
  
do
{
if(temp->getData() == val)
{
return true;
}
temp = temp->getNext();
} while (temp != NULL);
}
  
return false;
}

#endif /* DYNAMICARRAY_H */

Homework Answers

Answer #1

I didn't get segmentation fault for addElementBack. But in print i got. You have to check whether head is null or not before printing the values. This check is not there in your print function. That's why you got segmentation fault. The following is the program i tried and i fixed print function. But i'm didn't get segmentation fault in addElementBack. Please post your code (with main function) so that we can trace it.

Code:

main.cpp:

#include<iostream>
using namespace std;

#include "dynamicarray.h"

int main(void)
{
DynamicArray da;

da.print();
for(int i=10;i<60;i+=10)
da.addElementBack(i);

da.print();

return 0;
}

dynamicarray.cpp:

#include<stdio.h>
#include<iostream>
using namespace std;

#include "dynamicarray.h"
Node::Node()
{

}
Node::Node(int val)
{
data = val;
}
DynamicArray::DynamicArray()
{
head = NULL;
size = 0;
}
DynamicArray::DynamicArray(int s)
{
head = new Node();
  
for(int i = 0; i < s - 1; i++)
{
addElementBack(0);
}
  
size = s;
}
DynamicArray::~DynamicArray()
{
//delete all nodes
  
delete head;
}

/*
* Function that adds the given value to the front of the array
*/
void DynamicArray::addElementFront(int val)
{
if (head == NULL)
{
head = new Node(val);
head->SetNext(NULL);
}
else {
Node *newNode = new Node(val);
newNode->SetNext(head);
head->SetPrev(newNode);
head = newNode;
}
  
size++;
}
/*
* Function that adds the given value to the back of the array
*/
void DynamicArray::addElementBack(int val)
{
if (head == NULL)
{
head = new Node(val);
}
else if (head->getNext() == NULL)
{
Node* newNode = new Node(val);
head->SetNext(newNode);
newNode->SetPrev(head);
}
else {
Node *temp = head->getNext();
  
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
  
Node *newNode = new Node(val);
newNode->SetPrev(temp);
temp->SetNext(newNode);
}
  
size++;
}
/*
* Inserts a value at a given location. If the location in the array is
* filled, it shifts the values from that location on one time.
*/
void DynamicArray::insertElement(int loc, int val)
{
if(loc == 0) //insert at head
{
Node *newNode = new Node(val);
newNode->SetNext(head);
head = newNode;
}
else
{
Node *temp = head;
int step = 0;
  
while (step != loc - 1)
{
temp = temp->getNext();
step++;
}
  
temp->SetNext(new Node(val));
}
  
size++;
}
/*
* Subtracts a given value from an element at a given location. If the
* subtraction results in a negative number, that element is set to zero.
*/
void DynamicArray::delementelement(int loc, int val)
{
if(loc == 0) //delement head
{
head->SetData(head->getData() - val);
}
else
{
Node *temp = head;
int step = 0;
  
while (step != loc)
{
temp = temp->getNext();
step++;
}
  
temp->SetData(temp->getData() - val);
}
}
/*
* Deletes a given value from the array
*/
void DynamicArray::del(int val)
{
if (head == NULL)
{
printf("%s", "error: array is empty");
}
else if (head->getNext() == NULL && head->getData() == val)
{
head = NULL;
size--;
}
else
{
Node *temp = head->getNext();
bool found = false;
  
while (temp != NULL && !found)
{
if(temp->getData() == val)
{
(temp->getPrev())->SetNext(temp->getNext());
(temp->getNext())->SetPrev(temp->getPrev());
found = true;
}
  
temp = temp->getNext();
}
  
delete temp;
  
size--;
}
}
void DynamicArray::removeFront()
{
if (head == NULL)
{
printf("%s", "error: array is empty");
}
else
{
Node *temp = head;
head = head->getNext();
head->SetPrev(NULL);
delete temp;
size--;
}
}
void DynamicArray::removeBack()
{
if (head == NULL)
{
printf("%s", "error: array is empty");
}
else if (head->getNext() == NULL)
{
head = NULL;
size--;
}
else
{
Node *temp = head->getNext();
  
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
  
(temp->getPrev())->SetNext(NULL);
delete temp;
  
size--;
}
}
int DynamicArray::sizeArray()
{
return size;
}
void DynamicArray::print()
{
Node *temp = head;
  
if(temp==NULL) return;

do {
printf("%d", temp->getData());
temp = temp->getNext();
} while(temp != NULL);
  
printf("%s", "\n");
}
bool DynamicArray::contains(int val)
{
if (head == NULL)
{
return false;
}
else
{
Node *temp = head;
  
do
{
if(temp->getData() == val)
{
return true;
}
temp = temp->getNext();
} while (temp != NULL);
}
  
return false;
}

dynamicarray.h:

#ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H
#include <cstdlib>
#include <iostream>
using namespace std;
// Node class
class Node {
int data;
Node* next;
Node* prev;
public:
Node();
Node(int);
void SetData(int newData) { data = newData; };
void SetNext(Node* newNext) { next = newNext; };
void SetPrev(Node* newPrev) { prev = newPrev; };
int getData() { return data; };
Node* getNext() { return next; };
Node* getPrev() { return prev; };
};
class DynamicArray
{
Node *head;
int size;
public:
DynamicArray();
DynamicArray(int);
~DynamicArray(); //destructor to free memory
  
void addElementFront(int);
void addElementBack(int);
void insertElement(int, int);
void delementelement(int, int);
void del(int val);
void removeFront();
void removeBack();
  
int sizeArray();
bool contains(int);
  
void print();
  
};

#endif /* DYNAMICARRAY_H */

output:

10

20

30

40

50

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
This is the java code that I have, but i cannot get the output that I...
This is the java code that I have, but i cannot get the output that I want out of it. i want my output to print the full String Form i stead of just the first letter, and and also print what character is at the specific index instead of leaving it empty. and at the end for Replaced String i want to print both string form one and two with the replaced letters instead if just printing the first...
IN C++ PLEASE!!! What needs to be done is in the code itself where it is...
IN C++ PLEASE!!! What needs to be done is in the code itself where it is written TO DO List! #include<iostream> using namespace std; template<typename T> class DoubleList{​​​​​     class Node{​​​​​     public: T value; Node* next; Node* prev;         Node(T value = T(), Node* next = nullptr, Node* prev = nullptr){​​​​​             this->value = value;             this->next = next;             this->next = next;         }​​​​​     }​​​​​;     int size;     Node* head;     Node* tail; public:     DoubleList(){​​​​​         size = 0;         head = nullptr;     }​​​​​     int length(){​​​​​         return size;     }​​​​​...
i want to complete this code to insert a new node in the middle of list...
i want to complete this code to insert a new node in the middle of list (take a node data from user, search the node and insert new node after this node). this is the code #include <iostream> #include <stdlib.h> using namespace std ; struct Node{                int data;                Node *link ;}; struct Node *head=NULL, *tail=NULL; /* pointers to Node*/ void InsertFront(); void InsertRear(); void DeleteFront(); void DeleteRear(); int main(){                int choice;                do{                               cout << "1:...
Data Structure in C++ I keep getting the same warning, and I cant seem to fix...
Data Structure in C++ I keep getting the same warning, and I cant seem to fix it.. Can you explain to me what I am doing wrong? Warning: dlist.cc: In function 'std::ostream& operator<<(std::ostream&, dlist&)': dlist.cc:66:10: error: invalid initialization of reference of type 'std::ostream& {aka std::basic_ostream&}' from expression of type 'dlist::node*' dlist.cc: In function 'dlist operator+(dlist&, dlist&)': dlist.cc:93:8: error: invalid operands of types 'dlist::node*' and 'dlist::node*' to binary 'operator+' dlist.cc:97:8: error: could not convert 'result' from 'int' to 'dlist' My code:...
In this code, I build a single-linked list using a node class that has been created....
In this code, I build a single-linked list using a node class that has been created. How could I change this code to take data of type T, rather than int. (PS: ignore the fact that IOHelper.getInt won't work for the type T... ie second half of main). Here's my code right now: public class SLList { public SLNode head = null; public SLNode tail = null; public void add(int a) {// add() method present for testing purposes SLNode newNode...
For the following code in C, I want a function that can find "america" from the...
For the following code in C, I want a function that can find "america" from the char array, and print "america is on the list" else "america is not on the list" (Is case sensitive). I also want a function to free the memory at the end of the program. #include <stdio.h> #include <stdlib.h> struct Node { void *data; struct Node *next; }; struct List { struct Node *head; }; static inline void initialize(struct List *list) { list->head = 0;...
c++ data structures linked list delete node bool deleteNode(int); pass this method an id to delete....
c++ data structures linked list delete node bool deleteNode(int); pass this method an id to delete. Return true or false to indicate success or failure. Delete the memory the node was using The algorithm for deleting a Node to a Linked List (general case): ● Begin at the head. ● Compare the id to the current node. ● If search id > current id, stop. ● Detach the current Node ○ current->previous->next = current->next ○ current->next->previous = current->previous ● Deallocate...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>    #include <cstdlib> #include "QueueADT.h" using namespace std; // Definition of the node template <class ItemType> struct NodeType {        ItemType info;        NodeType<ItemType> *next; }; template <class ItemType> class LinkedQueueType: public QueueADT<ItemType> { public:        // Constructor        LinkedQueueType();           // Default constructor.           // Post: An empty queue has been created. queueFront = NULL;           //       queueBack = NULL;...
Java Language Add a method (convertToRing ()) that converts the list to a circular. This is,...
Java Language Add a method (convertToRing ()) that converts the list to a circular. This is, which makes the last node instead of pointing to null point to the first. Code: class Node { int value; Node nextNode; Node(int v, Node n) { value = v; nextNode = n; } Node (int v) { this(v,null); } } class LinkedList { Node head; //head = null; LinkedList() { } int length() { Node tempPtr; int result = 0; tempPtr = head;...
Java Language Add a method (convertToRing ()) that converts the list to a circular. This is,...
Java Language Add a method (convertToRing ()) that converts the list to a circular. This is, which makes the last node instead of pointing to null point to the first. Code: class Node { int value; Node nextNode; Node(int v, Node n) { value = v; nextNode = n; } Node (int v) { this(v,null); } } class LinkedList { Node head; //head = null; LinkedList() { } int length() { Node tempPtr; int result = 0; tempPtr = head;...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT