C++: Using cout causing change in value of a variable - c++

I was learning about how to use classes and wrote the following code:
#include<iostream>
using namespace std;
class DQNode
{
public:
int data;
DQNode *next, *last;
DQNode(int num, DQNode *n, DQNode *l)
{
data = num;
next = n;
last = l;
}
};
class Deque
{
private:
DQNode *top, *bottom;
int size;
public:
Deque()
{
top = NULL;
bottom = NULL;
size = 0;
}
void addFirst(int inp)
{
DQNode nn(inp, NULL, top);
if(top != NULL)
{
(*top).next = &nn;
}
top = &nn;
if(bottom == NULL)
{
bottom = &nn;
}
}
void PrintAll()
{
cout<<top->data<<endl;
}
};
int main()
{
Deque n;
n.addFirst(5);
cout<<"yo"<<endl;
n.PrintAll();
}
The above code prints "yo" followed by a random integer, interesting part is that on removing cout<<"yo"<<endl;the output is exactly as expected i.e 5.
So, if someone understands what is going wrong please help me.

You have undefined behavior.
This is what happens when you break the rules. When you're lucky, you program crashes with a segmentation fault. Other times, you're unlucky and your program misbehave.
How did you break the rules? Well, you access a dead object.
The source of the problem is happening in your addFirst function. You store a DQNode in your Deque but that node dies.
You see, all local variable with automatic storage have well defined rules for when they live and die. Their lifetime is scope based. It look like this:
// Lifetimes
void addFirst(int inp) // inp
{ // |
DQNode nn(inp, NULL, top); // | nn
if(top != NULL) // | |
{ // | |
(*top).next = &nn; // | +--- <- top->next
} // | |
top = &nn; // | +--- <- top
if(bottom == NULL) // | |
{ // | |
bottom = &nn; // | +--- <- bottom
} // | |
} // | X -- nn dies
// X -- inp dies
Variable with automatic lifetimes are first to live, last to die. There is no exceptions. At the } character at the end of the function, where its scope ends, all local variable are destroyed. nn first, then inp.
At that point, top, bottom or top->next is still pointing to nn, which has been destroyed!
Then, in your PrintAll function is reading through the pointers=, which point to a destroyed variable. At that point, you read whatever is on the stack in that point of the program. A simple call to cout can allocate variables in the places where nn was, and assign whatever needed values. You pointer will still point there, and print garbage.
What can you do about it?
Well, you don't want automatic storage. It doesn't do what you want. You want to take control over the lifetime of the variables and deallocate them when you decide when you don't need them anymore. This is called the free store. You create objects there using dynamic allocation:
void addFirst(int inp)
{
// new will dynamically allocate the object on the free store.
DQNode* nn = new DQNode(inp, NULL, top);
if(top != NULL)
{
(*top).next = nn;
}
top = nn;
if(bottom == NULL)
{
bottom = nn;
}
} // the `nn` pointer dies, but not the object it refers to!
However, your program will never deallocate the variable on its own, you must do it manually or you'll get a memory leak.
~Deque() {
// traverse the tree
// delete all node in the tree
}
Luckily, there is also a tool called a std::unique_ptr which will take care of deleting the allocated object when it dies.
The name unique_ptr comes from unique owner. The ownership of memory can be transferred, but there is always one and only one owner. When the owner dies, it deallocate the object from the free store:
// create a int equal to 1 on the free store using dynamic allocation
std::unique_ptr<int> int_a = std::make_unique<int>(1);
std::unique_ptr<int> int_b = nullptr;
// transfer ownership from int_a to int_b
int_b = std::move(int_a);
// int_a is null
// int_b point to a int equal to 1
// This is disallowed, you cannot have two owner, so no copy
// int_a = int_b;
// can have an observing raw pointer:
int* int_c = int_b.get();
// transfer ownership back
int_a = std::move(int_b);
// at that point int_a is equal to int_c
// int_a is the owner, int_c simply point to the same int.
// int_b is null
// Set the last owner to null:
int_a = nullptr;
// the int has been destroyed because there is no owner left.
// int_a is null, int_b is null
// int_c is a dangling pointer, point to the dead object.

Related

Hashtable AddEntry Separate Chaining Segmentation Fault

I am getting a segmentation fault in my Separate Chaining Hash Table object.
bool hashTable::addNode(int id, string information){
bool inserted = false;
int position = hash(id);
cout << &hashtable[position]<<endl;
if(hashtable[position]==NULL){
hashtable[position]->data.id = id;
hashtable[position]->data.information = information;
hashtable[position]->next = NULL;
inserted = true;
} else {
Node* current = new Node;
current = hashtable[position];
while(current!=NULL){
if(id < hashtable[position]->data.id){
current->data.id = id;
current->data.information = information;
current->next = hashtable[position];
hashtable[position] = current;
inserted = true;
} else if(id < current->data.id){
current->data.id = id;
current->data.information = information;
current->next = hashtable[position]->next;
hashtable[position]->next = current;
inserted = true;
} else if(current->next==NULL){
Node *temp;
temp->next = NULL;
temp->data.id = id;
temp->data.information = information;
current->next = temp;
inserted = true;
}
current = current->next;
}
}
return inserted;
}
Essentially, I have an array of head pointers to handle the separate chaining, but the segmentation fault in addNode is messing me up. To be clear, I am calling a public AddEntry first which calls the AddNode for each individual LinkedList in the array.
#ifndef HASH_H
#define HASH_H
#include <iostream>
#include <string>
#include "data.h"
using std::string;
using std::cout;
using std::endl;
#define SIZE 15
class hashTable{
public:
hashTable();
~hashTable();
bool addEntry(int id, string information);
string getEntry(int id);
bool removeEntry(int id);
int getCount();
void displayTable();
private:
bool removeNode(int id, int position);
bool addNode(int id, string information);
int count = 0;
Node* hashtable = new Node[SIZE]; //array of head pointers
int hash(int id);
};
#endif
Sorry if I didn't word this the best this is my first time on Stack Overflow.
There are a few spots in your code where it looks like you're using the address-of operator & incorrectly. Let's start with this one:
if (&hashtable[position] == NULL) {
...
}
I completely see what you're trying to do here - you're trying to say "if the slot at index position holds a null pointer." However, that's not what this code actually does. This says "if the location in memory where hashtable[position] exists is itself a null pointer." That's not possible - hashtable[position] refers to a slot in an array - so this if statement never fires.
It might be helpful to draw pictures here to get a better sense of what's going on. For example, suppose you have an empty hash table, as shown here:
+-------+ +------+------+------+------+ +------+
| |------>| null | null | null | null | ... | null |
+-------+ +------+------+------+------+ +------+
hashtable
Here, hashtable[position] refers to the pointer at index position in the array pointed at by hashtable. With an empty hash table, hashtable[position] will evaluate to NULL because that's the contents of the pointer at that slot. On the other hand, &hashtable[position] refers to something like this:
&hashtable[position]
+-------+
| |
+-------+
|
v
+-------+ +------+------+------+------+ +------+
| |------>| null | null | null | null | ... | null |
+-------+ +------+------+------+------+ +------+
hashtable
Here, &hashtable[position] points to one of the pointers in the array. And while the pointer &hashtable[position] is pointing at something that is a null pointer, it itself is not a null pointer, since it's pointing to a valid object in memory.
Changing the code to read
if (hashtable[position] == NULL) {
...
}
correctly expresses the idea of "if the entry at index position within the hashtable array isn't a null pointer."
There are similar errors in your code at a few other points. Read over what you have with an eye toward the following question: do I want the pointer stored in the array at some index, or do I want the location in memory where that pointer happens to live?

Iterating over linked list in C++ is slower than in Go with analogous memory access

In a variety of contexts I've observed that linked list iteration is consistently slower in C++ than in Go by 10-15%. My first attempt at resolving this mystery on Stack Overflow is here. The example I coded up was problematic because:
1) memory access was unpredictable because of heap allocations, and
2) because there was no actual work being done, some people's compilers were optimizing away the main loop.
To resolve these issues I have a new program with implementations in C++ and Go. The C++ version takes 1.75 secs compared to 1.48 secs for the Go version. This time, I do one large heap allocation before timing begins and use it to operate an object pool from which I release and acquire nodes for the linked list. This way the memory access should be completely analogous between the two implementations.
Hopefully this makes the mystery more reproducible!
C++:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/timer.hpp>
using namespace std;
struct Node {
Node *next; // 8 bytes
int age; // 4 bytes
};
// Object pool, where every free slot points to the previous free slot
template<typename T, int n>
struct ObjPool
{
typedef T* pointer;
typedef pointer* metapointer;
ObjPool() :
_top(NULL),
_size(0)
{
pointer chunks = new T[n];
for (int i=0; i < n; i++) {
release(&chunks[i]);
}
}
// Giver an available pointer to the object pool
void release(pointer ptr)
{
// Store the current pointer at the given address
*(reinterpret_cast<metapointer>(ptr)) = _top;
// Advance the pointer
_top = ptr;
// Increment the size
++_size;
}
// Pop an available pointer off the object pool for program use
pointer acquire(void)
{
if(_size == 0){throw std::out_of_range("");}
// Pop the top of the stack
pointer retval = _top;
// Step back to the previous address
_top = *(reinterpret_cast<metapointer>(_top));
// Decrement the size
--_size;
// Return the next free address
return retval;
}
unsigned int size(void) const {return _size;}
protected:
pointer _top;
// Number of free slots available
unsigned int _size;
};
Node *nodes = nullptr;
ObjPool<Node, 1000> p;
void processAge(int age) {
// If the object pool is full, pop off the head of the linked list and release
// it from the pool
if (p.size() == 0) {
Node *head = nodes;
nodes = nodes->next;
p.release(head);
}
// Insert the new Node with given age in global linked list. The linked list is sorted by age, so this requires iterating through the nodes.
Node *node = nodes;
Node *prev = nullptr;
while (true) {
if (node == nullptr || age < node->age) {
Node *newNode = p.acquire();
newNode->age = age;
newNode->next = node;
if (prev == nullptr) {
nodes = newNode;
} else {
prev->next = newNode;
}
return;
}
prev = node;
node = node->next;
}
}
int main() {
Node x = {};
std::cout << "Size of struct: " << sizeof(x) << "\n"; // 16 bytes
boost::timer t;
for (int i=0; i<1000000; i++) {
processAge(i);
}
std::cout << t.elapsed() << "\n";
}
Go:
package main
import (
"time"
"fmt"
"unsafe"
)
type Node struct {
next *Node // 8 bytes
age int32 // 4 bytes
}
// Every free slot points to the previous free slot
type NodePool struct {
top *Node
size int
}
func NewPool(n int) NodePool {
p := NodePool{nil, 0}
slots := make([]Node, n, n)
for i := 0; i < n; i++ {
p.Release(&slots[i])
}
return p
}
func (p *NodePool) Release(l *Node) {
// Store the current top at the given address
*((**Node)(unsafe.Pointer(l))) = p.top
p.top = l
p.size++
}
func (p *NodePool) Acquire() *Node {
if p.size == 0 {
fmt.Printf("Attempting to pop from empty pool!\n")
}
retval := p.top
// Step back to the previous address in stack of addresses
p.top = *((**Node)(unsafe.Pointer(p.top)))
p.size--
return retval
}
func processAge(age int32) {
// If the object pool is full, pop off the head of the linked list and release
// it from the pool
if p.size == 0 {
head := nodes
nodes = nodes.next
p.Release(head)
}
// Insert the new Node with given age in global linked list. The linked list is sorted by age, so this requires iterating through the nodes.
node := nodes
var prev *Node = nil
for true {
if node == nil || age < node.age {
newNode := p.Acquire()
newNode.age = age
newNode.next = node
if prev == nil {
nodes = newNode
} else {
prev.next = newNode
}
return
}
prev = node
node = node.next
}
}
// Linked list of nodes, in ascending order by age
var nodes *Node = nil
var p NodePool = NewPool(1000)
func main() {
x := Node{};
fmt.Printf("Size of struct: %d\n", unsafe.Sizeof(x)) // 16 bytes
start := time.Now()
for i := 0; i < 1000000; i++ {
processAge(int32(i))
}
fmt.Printf("Time elapsed: %s\n", time.Since(start))
}
Output:
clang++ -std=c++11 -stdlib=libc++ minimalPool.cpp -O3; ./a.out
Size of struct: 16
1.7548
go run minimalPool.go
Size of struct: 16
Time elapsed: 1.487930629s
The big difference between your two programs is that your Go code ignores errors (and will panic or segfault, if you're lucky, if you empty the pool), while your C++ code propagates errors via exception. Compare:
if p.size == 0 {
fmt.Printf("Attempting to pop from empty pool!\n")
}
vs.
if(_size == 0){throw std::out_of_range("");}
There are at least three ways1 to make the comparison fair:
Can change the C++ code to ignore the error, as you do in Go,
Change both versions to panic/abort on error.
Change the Go version to handle errors idiomatically,2 as you do in C++.
So, let's do all of them and compare the results3:
C++ ignoring error: 1.059329s wall, 1.050000s user + 0.000000s system = 1.050000s CPU (99.1%)
C++ abort on error: 1.081585s wall, 1.060000s user + 0.000000s system = 1.060000s CPU (98.0%)
Go panic on error: Time elapsed: 1.152942427s
Go ignoring error: Time elapsed: 1.196426068s
Go idiomatic error handling: Time elapsed: 1.322005119s
C++ exception: 1.373458s wall, 1.360000s user + 0.000000s system = 1.360000s CPU (99.0%)
So:
Without error handling, C++ is faster than Go.
With panicking, Go gets faster,4 but still not as fast as C++.
With idiomatic error handling, C++ slows down a lot more than Go.
Why? This exception never actually happens in your test run, so the actual error-handling code never runs in either language. But clang can't prove that it doesn't happen. And, since you never catch the exception anywhere, that means it has to emit exception handlers and stack unwinders for every non-elided frame all the way up the stack. So it's doing more work on each function call and return—not much more work, but then your function is doing so little real work that the unnecessary extra work adds up.
1. You could also change the C++ version to do C-style error handling, or to use an Option type, and probably other possibilities.
2. This, of course, requires a lot more changes: you need to import errors, change the return type of Acquire to (*Node, error), change the return type of processAge to error, change all your return statements, and add at least two if err != nil { … } checks. But that's supposed to be a good thing about Go, right?
3. While I was at it, I replaced your legacy boost::timer with boost::auto_cpu_timer, so we're now seeing wall clock time (as with Go) as well as CPU time.
4. I won't attempt to explain why, because I don't understand it. From a quick glance at the assembly, it's clearly optimized out some checks, but I can't see why it couldn't optimize out those same checks without the panic.

C++ Pointers and Data Locations: Data Always Being Placed at Same Memory Location

I'm trying to implement an iterative deepening depth first search algorithm in C++. The search successfully finds the solution to the problem, but I am having trouble linking the child node back to the root node.
struct Node
{
std::vector<int> config;
int depth;
int action; //0 up 1 down 2 left 3 right
Node * parent;
bool operator<(const Node& rhs) const
{
return depth < rhs.depth;
}
};
As you can see in my structure, I have a pointer to the parent node. In my DFS code however, I am running into a problem updating the parent pointer for the nodes in each iteration of the loop. The parent pointer for all nodes always points to the same data location, 0xfffffffd2b0. In other words, the new node called Next is always created here.
I believe the Node I have in my code called Next always gets placed at this same data locataion, thus the reference location to each Next is always the same. How can I prevent it from always appearing at the same location? This means that the Child nodes are not being linked to their parent, but rather to themselves. I have marked the source of the bug with asterisks.
//IDDFS Logic:
int Current_Max_Depth = 0;
while(Current_Max_Depth < 20)
{
struct Node initial = {orig_config, 0, 0, NULL}; //config, depth, action, parent.
visited.clear();
priority_queue<Node> frontier;
frontier.push(initial);
while(frontier.size()>0)
{
struct Node Next = frontier.top();
visited.push_back(Next.config);
frontier.pop();
if(Next.depth < Current_Max_Depth)
{
int pos_of_hole = Find_Position_of_Hole(Next.config);
if(pos_of_hole==0)
{
std::vector<int> Down_Child = Move_Down(Next.config);
struct Node Down_Node = {Down_Child,Next.depth+1,1,&Next}; //****
if(!(std::find(visited.begin(), visited.end(), Down_Child)!=visited.end()))
{
if(Goal_Test(Down_Child))
{
goal_node = Down_Node;
goal_reached = true;
break;
}
frontier.push(Down_Node);
}
std::vector<int> Right_Child = Move_Right(Next.config);
struct Node Right_Node = {Right_Child,Next.depth+1,3,&Next}; //*******Passing next by reference here is not working since Next is always at the same data location. The nodes one layer up from the leaf nodes end up all pointing to themselves.
if(!(std::find(visited.begin(), visited.end(), Right_Child)!=visited.end()))
{
if(Goal_Test(Right_Child))
{
goal_node = Right_Node;
goal_reached = true;
break;
}
frontier.push(Right_Node);
}
}
if(pos_of_hole==1)
... does very similar for pos 1 through 8, not related to bug ...
} //End of if(Next.Depth < Max_Depth)
} //End of while(frontier.size()>0)
if(goal_reached)
{
break;
}
Current_Max_Depth++;
}
struct Node initial = {orig_config, 0, 0, NULL};
Creates a Node on the stack. When you create the next child
struct Node Down_Node = {Down_Child,Next.depth+1,1,&Next};
You are taking the address of that local stack object. When the loop ends Next is destroyed and then it is constructed again at the beginning of the next iteration of the while loop. If the nodes need to persist then you need to allocate them with new and then delete then when you are done.
On a side note the struct keyword is not required on variable declarations in C++. See Why does C need “struct” keyword and not C++? for more information.

Why is my class' destructor being called when leaving the scope of a private function belonging to the class?

I've been refreshing myself with C++ and am trying to create a linked list class with 2 strings that has a function which will sort items in the list alphabetically. I send them to a swap function by passing pointers to the two items in the list being compared and then they trade pointer information so that the list is "reorganized", as shown here:
void LinkedList::swapItem(LinkedList* a, LinkedList* b)
{
LinkedList temp = *a;
a->pNext = b->pNext;
// if statement to prevent b->pNext from pointing back to b if items are 'adjecent' to eachother in the list
if(b == temp.pNext)
{
b->pNext = a;
}
else
{
b->pNext = temp.pNext;
}
a->idNum = b->idNum;
b->idNum = temp.idNum;
}
This function is called by another function which is supposed to check the values of the "last name" string and determine if they need to be swapped. Then it switches the iterators(which are the pointers that were passed in to the swap function), and is supposed to continue through the list, but after the swap function, the iterators/pointers point to the same place but the data in the objects is just gone because the destructor is called at the end of the swap function! why would it call the destructor when the objects are still being used? Is there a way to tell the destructor to stop? Here is the code for sorting alphabetically:
LinkedList* LinkedList::sortAlpha()
{
LinkedList *top = this;
LinkedList *pItrA = this;
LinkedList *pItrB = this->pNext;
LinkedList *temp = NULL;
while(pItrA != NULL)
{
while(pItrB != NULL)
{
if(pItrA->alphaOrder > pItrB->alphaOrder)
{
swapItem(pItrA, pItrB);
temp = pItrA;
pItrA = pItrB;
pItrB = temp;
temp = NULL;
if(pItrB->idNum == 0)
{
// Tracks the pointer at the "top" of the list if pItrB is the new top item
top = pItrB;
}
}
pItrB = pItrB->pNext;
}
pItrA = pItrA->pNext;
}
return top;
}
I know this code is probably VERY messy, or at best inefficient, but I'm not too concerned about that because I'm just trying to understand how it all works and why.
This creates a local temporary LinkedList, initialized by copying a into it:
LinkedList temp = *a;
When that temporary goes out of scope, its destructor gets called. That is what is supposed to happen, and you can't stop it without eliminating the temporary.
You should rewrite your swap function so that it doesn't require making a copy of a in this way. It doesn't seem like you can make your current swap function correct unless you do so.
One of two things are likely happening when you create this temporary:
The copy constructor does a shallow copy, bringing over pointers from the source.
The copy constructor does a deep copy on plain pointers, and replicates the structure.
You use reference-counted pointers and do something much fancier.
The shallow copy lets you test pointers directly, as you do in your swap function. A deep copy would give you unrelated pointers between the two copies. And #3 seems unlikely at the moment.
Then, when you destroy the temporary, a couple different things might be happening:
You don't delete anything, leading to potential memory leaks.
You delete the entire chain starting at the temporary, obliterating a good portion of your linked list (assuming a shallow copy).
I'm guessing since you came here, the situation looks closer to #2.
Including my further thoughts from below: Your swap logic looks flawed. To swap items in a singly linked list, you need to manipulate the next pointers of the predecessors to the swapped nodes, and you do not have those available to you in your swap function.
In this case, you're better off just swapping the other members of the class, as opposed to manipulating pointers. If your class had a large amount of data in it, then you might be better off with pointer manipulation, but you need to know the predecessors of the two nodes you're swapping (or at least a pointer/reference to the pNext in the predecessors) to do it correctly.
The variable temp is being destroyed, and presumably destroying the other LinkedList objects that it points to. Instead, rewrite as:
void LinkedList::swapItem(LinkedList* a, LinkedList* b)
{
LinkedList* tmpNext = a->pNext;
auto tmpId = a->idNum; // I use auto because I don't know what type idNum is (int ?)
a->pNext = b->pNext;
// if statement to prevent b->pNext from pointing back to b if items are 'adjecent' to eachother in the list
if(b == tmpNext)
{
b->pNext = a;
}
else
{
b->pNext = tmpNext;
}
a->idNum = b->idNum;
b->idNum = tmpId;
}
Joe Z was correct with
You delete the entire chain starting at the temporary, obliterating a good portion of your linked list (assuming a shallow copy)
So I rewrote the alphaSort function to handle everything:
LinkedList* LinkedList::sortAlpha()
{
bool sorted = false;
LinkedList* top = this;
LinkedList* prev = NULL;
LinkedList* itr = NULL;
while(sorted == false)
{
prev = NULL;
itr = top;
sorted = true;
while(itr != NULL)
{
if(itr->pNext != NULL && itr->alphaOrder > itr->pNext->alphaOrder)
{
LinkedList *temp = itr;
LinkedList *tempNext = itr->pNext->pNext;
if(itr->idNum == 0)
{
itr->idNum = itr->pNext->idNum;
itr->pNext->idNum = 0;
top = itr->pNext;
}
itr = itr->pNext;
itr->pNext = temp;
itr->pNext->pNext = tempNext;
sorted = false;
if(prev != NULL)
{
prev->pNext = itr;
}
}
prev = itr;
itr = itr->pNext;
}
}
itr = top;
int idCounter = 0;
while(itr != NULL)
{
itr->idNum = idCounter;
idCounter++;
itr = itr->pNext;
}
return top;
}
Thanks for the input everyone!

Error When implementing a circular Queue?

I had to implement a circular queue for class. The program properly Enqueues and Dequeues when I test it. But whenever I create a new object and set it equal to another, everything prints out correctly, but it crashes at the end, with an error:
Expression: _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse)
I ran the debugger and it says the problem is in a line in the Dequeue function. Here is That function.
void CQUEUE::Dequeue()
{
if(Isempty())
{
cout << "Queue is empty, nothing to delete." << endl;
return;
}
if((!Isempty()) && (front == back)) //When there is only 1 item in the queue
{ // front and back will point to the same node
delete front; //but it wont be null because of that 1 item
front = back = 0;
return;
}
qnode *p = front;
front = front -> next;
delete p;//<----------DEBUGGER POINTS HERE**************
front -> prev = back;
return;
}
Like I said, the program works fine until I create a new object and do this
CQUEUE j = k;//Any Enqueues and Dequeues after this work, but it crashes
Here is the copy constructor incase that is the problem?
CQUEUE::CQUEUE(CQUEUE & original)//Will not compile if I put Const
{ //in the parameter for some reason
front = back = 0; //So I took it out
(*this) = original;
front -> prev = back;
back -> next = front;
}
In your copy constructor you do the following:
(*this) = original;
The means that your front pointers in CQUEUE j and CQUEUE k both point to the same memory.
When void CQUEUE::Dequeue() is called for both j and k, delete p; double deletes the memory, resulting in a crash.
Also, your copy constructor must be declared as const. CQUEUE::CQUEUE(const CQUEUE& original). Without more code is hard to say, but in your copy constructor you need to make deep copies of the pointers (allocate memory using new). Reading What is The Rule of Three? might help.