C++ Pointer target returning wrong value - c++

I am a fairly experience C# programmer and trying to help out a friend with a C++ application that creates a Stack object. It has been well over 13 years since I've even seen C++ and I am having a damn fine time trying to recall the proper way to do this. It took me a bit to get up to speed on the Header/CPP distinction again, so there may be issues in there even. Here is my problem:
//Stack.h
#ifndef __STACK_INCLUDED__
#define __STACK_INCLUDED__
#include "Node.h"
class Stack
{
private:
/// Going to be the pointer to our top node
Node* m_topNode;
/// Running count of elements
int m_count;
public:
///Constructor
Stack();
///Allows us to retrieve the top value from the stack
/// and remove it from the stack
int Pop();
.
.
.
};
#endif
Below is the CPP that matches the header. I am doing in here JUST for debugging at the moment. I am also fully qualifying everything because I was not sure if that is causing issues with the pointers and loss of references.
//Stack.cpp
#include "stdafx.h"
#include "Stack.h"
#include <iostream>
Stack::Stack(){
m_count = 0;
m_topNode = NULL;
}
void Stack::Push(int Value){
std::cout << "\nPushing Value: ";
std::cout << Value;
std::cout << "\n";
if ( Stack::m_topNode )
{
std::cout << "TopNode Value: ";
std::cout << Stack::m_topNode->data;
std::cout << "\n";
}
std::cout << "\n";
Node newNode(Value, NULL, Stack::m_topNode);
Stack::m_topNode = &newNode;
Stack::m_count++;
}
The node class is a pretty simple entity. Just needs to store a value and the pointers on either side. I know I don't need to track in both directions for a Stack but I wanted to make this something that was easily changed to a Queue or similar construct.
//Node.h
#ifndef __NODE_INCLUDED__
#define __NODE_INCLUDED__
class Node
{
private:
public:
///Constructor allows us to specify all values.
/// In a stack I expect NextNode to be NULL
Node(int Value,Node* NextNode, Node* PreviousNode);
///Pointer to the next node
Node* Next;
///Pointer to the previous node
Node* Prev;
///Value to be stored
int data;
};
#endif
Very simple implementation:
//Node.cpp
#include "stdafx.h"
#include "Node.h"
Node::Node(int Value, Node* NextNode, Node* PreviousNode){
data = Value;
Next = NextNode;
Prev = PreviousNode;
}
My main is just about sending 2 values to the stack right now via Push and seeing what the values are printing:
#include "stdafx.h"
#include "Node.h"
#include "Stack.h"
using namespace std;
int main(){
Stack s = Stack();
for ( int i = 0; i < 2; i++ ){
s.Push(i * 10);
}
int blah;
cin >> blah; //Stall screen
return 0;
}
Here is the Output:
Pushing Value: 0
<blank line>
Pushing Value: 10
TopNode Value: -858993460
When I hit Node newNode(Value, NULL, Stack::m_topNode) in the debugger I can see it tracking the proper value in the current node, but m_topNode references a really odd value. I'm hoping it's very obvious that I'm doing something dumb as I don't remember this being this tricky when I did it years ago. Appreciate any help/insight to my incorrect manners.

Node newNode(Value, NULL, Stack::m_topNode);
Stack::m_topNode = &newNode;
Stack::m_count++;
This is your problem. You allocate the new node on the current stack, and then put the pointer into the linked list of nodes. This pointer will be invalid as soon as your stack frame returns, and all hell breaks lose. ;)
You need to allocate the node with new.

As stated by Norwæ, you need to allocate your newNode with "new" because if you dont, your newNode is static and will be out of scope at the end of the Push function.
You also need to call your private members without the "Stack::" as this is used in C++ only to access static class members and functions. replace "Stack::m_topNode" for "m_topNode" only, and Stack::m_count for m_count.
Here is a working Push function :
void Stack::Push(int Value){
std::cout << "\nPushing Value: ";
std::cout << Value;
std::cout << "\n";
if ( m_topNode )
{
std::cout << "TopNode Value: ";
std::cout << m_topNode->data;
std::cout << "\n";
}
std::cout << "\n";
Node * newNode = new Node(Value, NULL, m_topNode);
m_topNode = newNode;
m_count++;
}

This line:
std::cout << Stack::m_topNode->data;
happens before
Node newNode(Value, NULL, Stack::m_topNode);
Stack::m_topNode = &newNode;
Stack::m_count++;
So you're trying to print an uninitialized value. Reverse these and see what happens.

Related

Why is the constructor of the class called four times, and the destructor is only called twice when the program is about to end?

Why is the constructor of the class called four times, and the destructor is only called twice when the program is about to end?
I want to construct a one-way circular linked list and it's OK, but I got some problems on the destructor of the Bufferclass.
The code is as follows:
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class Buffer
{
public:
Buffer(): Next(nullptr)
{
int id = ID + 1;
ID++;
std::cout << "Thi is the " << id << "th buffer." << endl;
}
~Buffer()
{
cout << "The buffer is destructed." << endl;
}
shared_ptr<Buffer> Next;
static int ID;
};
int Buffer::ID = 0;
int main()
{
int LogBufferNum = 4;
shared_ptr<Buffer> Head = std::make_shared<Buffer>();
Head->Next = Head;
LogBufferNum--;
while (LogBufferNum > 0)
{
std::shared_ptr<Buffer> New = std::make_shared<Buffer>();
std::shared_ptr<Buffer> Temp(Head);
New->Next = Head;
Temp->Next = New;
Temp = New;
LogBufferNum--;
}
return 0;
}
it prints as:
The is the 1th buffer.
The is the 2th buffer.
The is the 3th buffer.
The buffer is destructed.
The is the 4th buffer.
The buffer is destructed.
Any solutions? Thank you very much
When you create a circular reference with shared_ptr, i.e. A contains a pointer to B and B contains a pointer to A, those object will never be destroyed. In this case two of your Buffers are pointing to each other. Try working out on paper what you are doing when you set up those pointers and you will see the circular reference.

C++ executable crashing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am starting to create a binary tree. So far all I have added is an insert function and I believe it works fine. When I compile my application, header and implementation files together it produces a executable but with an error code above it about exception handler used.... When I go to run the executable it crashes. I don't understand why it is crashing, can someone please help! Thanks in advance.
The command line errors http://gyazo.com/7ca1e8fb1a66da39e927e9ba627d3f53
My application file called mainprogramming.cpp
#include <iostream>
#include <cstdlib>
#include "Header.h"
using namespace std;
int main()
{
int Rndnums[10] = {3, 99, 76, 49, 32, 9, 77, 64, 81, 24};
BinaryTree *tree = new BinaryTree();
for(int i = 0; i < 10; i++)
{
tree->insert(Rndnums[i]);
}
return 0;
}
My header file called Header.h
class BinaryTree
{
// Can only be accessed by the class itself
private:
struct node
{
// Data stored in this node of he tree
int data;
// The left branch of the tree
node *left;
// The right branch of the tree
node *right;
};
node *tree;
void insert(node *tree, int value);
// Can be accessed by all
public:
BinaryTree(){};
~BinaryTree();
void insert(int value);
};
My implementation file called implementation.cpp
#include <iostream>
#include <cstdlib>
#include "Header.h"
using namespace std;
// Inserts a value into the tree - notice **
void BinaryTree::insert(node *tree, int value)
{
// Check if nullptr. If so set new node
if (tree == nullptr)
{
// Create new node
tree = new node;
// Set new value
tree->data = value;
// Set branches to nullptr
tree->left = nullptr;
tree->right = nullptr;
}
// If the input value is less than the node in the tree
else if(value < tree->data)
{
insert(tree->left, value);
cout << "The value " << value << "has been added as a left child\n";
}
// If the input value is greater than the node in the tree
else if(value > tree->data)
{
insert(tree->right, value);
cout << "The value " << value << "has been added as a right child\n";
}
else
{
cout << "The value " << value << "can only be equal and must already exist in the tree\n";
}
}
void BinaryTree::insert(int value)
{
insert(this->tree, value);
cout << "It ran";
}
Your problem is in your insert call:
void BinaryTree::insert(node * leaf_head, int value)
{
...
}
You are copying the pointer address then trying to create an object in that memory space, and then modifying that object. It works fine when you change it to a reference to that pointer:
void BinaryTree::insert(node * & leaf_head, int value)
{
...
}
That way you are actually modifying the tree pointer within BinaryTree instead of a copy of it.

Linked-List only remembers most recent added object

I have an assignment that requires me to add objects into a linked list. The objects in question are Shapes.
My problem is that I can add objects to the list, but when I try to print them out, only the last added object is printed, the rest are just trash values.
My code looks like this:
Source.cpp:
#include "ShapeList.h"
#include <iostream>
using namespace std;
int main()
{
ShapeList list;
list.add(Rectangle(0,0,2,5));
list.print();
}
I am not allowed to change this code. For example, I am not allowed to send a pointer to the new rectangle, I'm supposed to "deep-copy" it. (I hope I'm using that word right.)
My ShapeList.h looks like this:
#ifndef SHAPELIST_H
#define SHAPELIST_H
#include "Shape.h"
#include "Rectangle.h"
class ShapeList
{
private:
Shape *conductor; //this will point to each node as it traverses the list
Shape *root; //the unchanging first node
public:
ShapeList();
void print();
void add(const Shape &s);
};
#endif
and the header looks like:
#include "ShapeList.h"
#include <iostream>
using namespace std;
ShapeList::ShapeList()
{
cout << "ShapeList created" << endl;
root = new Shape; //now root points to a node class
root->next = 0; //the node root points to has its next pointer set to equal a null pointer
conductor = root; //the conductor points to the first node
}
void ShapeList::add(const Shape &s)
{
cout << "Shapelist's add function called" << endl;
conductor->next = new Shape; //creates node at the end of the list
conductor = conductor->next; //goes to next node
Shape *pShape = s.clone(); //get a pointer to s
conductor->current = pShape; //points current to pShape point
conductor->next = 0; //prevents loops from going out of bounds
}
void ShapeList::print()
{
conductor = root; //the conductor points to the start of the linked list
if(conductor != 0)
{
while(conductor->next != 0)
{
conductor = conductor->next;
cout << conductor->current->width << endl;
}
//cout << conductor->current->width << endl;
}
}
The clone-function is overloaded in all shapes, in this case it's the rectangle's:
Rectangle * Rectangle::clone() const
{
cout << "Rectangle's clone function called" << endl;
Rectangle copiedRect(this);
Rectangle * pCopiedRect = &copiedRect;
return pCopiedRect;
}
Rectangle::Rectangle(const Rectangle *ref)
{
cout << "Rectangle's copy constructor called" << endl;
this->x = ref->x;
this->y = ref->y;
this->width = ref->width;
this->height = ref->height;
}
I know it's alot to read, and I'm sorry. I can remove stuff if it's not needed. I can also add more if you would like.
I have read Alex Allain's tutorial* about linked lists, and a couple of other articles. If anyone has another article, or something like that, to suggest I'm all ears.
http://www.cprogramming.com/tutorial/c/lesson15.html
Rectangle::clone() is invoking undefined behavior. You're returning the address of an automatic variable copiedRect, which falls of scope as soon as the function terminates.
Try this:
Rectangle * Rectangle::clone() const
{
cout << "Rectangle's clone function called" << endl;
return new Rectangle(*this);
}
And your copy-ctor should not even need to be implemented. All the members of Rectangle are trivially copyable. The default should work fine.
Note: I didn't really take the time to dissect your list insertion code, but the above is definitely a problem that needs to be addressed.

C++ Stack Push/Print Implementation

I'm trying to make a stack implementation in C++ but when I try to print the stack,
it just prints the first element instead of the whole stack.
I've tested it and I'm pretty sure that my Push function is right, but I'm not sure.
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
int main(){
StackElement *stack = new StackElement();
stack->data = 20;
stack->Push(30,stack);
stack->Push(40,stack);
stack->Print(stack);
}
#include <stdio.h>
#include <stdlib.h>
class StackElement{
public:
int data;
StackElement* next;
StackElement();
void StackElement::Push(int value, StackElement *oldElement);
void StackElement::Print(StackElement *element);
};
StackElement::StackElement(){
next = NULL;
}
void StackElement::Push(int value, StackElement *oldElement){
StackElement *newElement = new StackElement();
newElement->data = value;
printf("Element added to stack: %d\n", newElement->data);
oldElement->next = newElement;
}
void StackElement::Print(StackElement *element){
while(element->next != NULL){
printf("%d\n",element->data);
element = element->next;
}
}
Your code kept loosing the previous pushed element, leaking memory, as #Beta described.
I suggest comparing my code below to your code. You'll see, I've moved the handling of the stack elements outside, just to be able to keep track of the first element. Also, notice that there is no pointer in the main function. That is what we expect from a class.
Stack_element is a struct really as there's not much point in making the Stack_element itself encapsulated, it is just an implementation detail of Stack.
So here's my code derived from yours
#include<iostream>
struct Stack_element{
int data;
Stack_element*next;
};
class Stack{
private:
Stack_element*last_data, first_data;
public:
Stack():last_data(NULL), first_data(NULL){}
void push(int data);
void print() const;
};
void Stack::push(int data)
{
Stack_element*p=new Stack_element();
p->data=data;
p->next=NULL;
if(last_data)
last_data->next=p;
else // empty stack
first_data=p;
last_data=p;
}
void Stack::print()
{
for(Stack_element*p=first_data;p;p=p->next)
std::cout << p->data << std::endl; // ** Do not use printf in c++. Ever. **
}
and in the main function just call
Stack stack;
stack.push(30);
stack.push(40);
stack.print();
REMARK: For a C++ish print you might want to do an ostream& print(ostream& os) instead, where
std::ostream& Stack::print(std::ostream& os)
{
for(Stack_element*p=first_data;p;p=p->next)
os << p->data << std::endl;
return os;
}
just to be able to write std::cout << stack.print() << std::endl;. The benefit of this is that you can easily redirect to a file.
std::ofstream ofs("yourfile.txt");
ofs << stack.print() << std::endl; // prints to file instead of screen.
Suppose this much works as planned:
StackElement *stack = new StackElement();
stack->data = 20;
stack->Push(30,stack);
Now your data looks like [20]->[30]
Now you attempt
stack->Push(40,stack);
So the Push method creates a new StackElement, gives it the value 40, and sets Stack to point to it: [20]->[40]. Notice that [30] has been lost.
Then the Print function:
while(element->next != NULL){
printf("%d\n",element->data);
element = element->next;
}
If there is only one element (whose next is NULL), this function will quit and print nothing. If there are two, this function will print the data of the first, then quit. And there will never be more than two, as long as Push has that bug.

Memory leak in trivial stack implementation

I'm decently experienced with Python and Java, but I recently decided to learn C++. I decided to make a quick integer stack implementation, but it has a massive memory leak that I can't understand. When I pop the node, it doesn't seem to be releasing the memory even though I explicitly delete the old node upon poping it. When I run it, it uses 150mb of memory, but doesn't release any of it after I empty the stack. I would appreciate any help since this is my first foray into a language without garbage collection. This was compiled with gcc 4.3 on 64-bit Kubuntu.
//a trivial linked list based stack of integers
#include <iostream>
using namespace std;
class Node
{
private:
int num;
Node * next;
public:
Node(int data, Node * next);
int getData();
Node * getNext();
};
Node::Node(int data, Node * next_node)
{
num = data;
next = next_node;
}
inline int Node::getData()
{
return num;
}
inline Node* Node::getNext()
{
return next;
}
class Stack
{
private:
unsigned long int n;
Node * top;
public:
Stack(int first);
Stack();
void push(int data);
int pop();
int peek();
unsigned long int getSize();
void print();
void empty();
};
Stack::Stack(int first)
{
Node first_top (first, NULL);
top = &first_top;
n = 1;
}
Stack::Stack()
{
top = NULL;
n = 0;
}
void Stack::push(int data)
{
Node* old_top = top;
Node* new_top = new Node(data,old_top);
top = new_top;
n++;
}
int Stack::pop()
{
Node* old_top = top;
int ret_num = old_top->getData();
top = old_top->getNext();
delete old_top;
n--;
return ret_num;
}
inline int Stack::peek()
{
return top->getData();
}
inline unsigned long int Stack::getSize()
{
return n;
}
void Stack::print()
{
Node* current = top;
cout << "Stack: [";
for(unsigned long int i = 0; i<n-1; i++)
{
cout << current->getData() << ", ";
current = current->getNext();
}
cout << current->getData() << "]" << endl;
}
void Stack::empty()
{
unsigned long int upper = n;
for(unsigned long int i = 0; i<upper; i++)
{
this->pop();
}
}
Stack createStackRange(int start, int end, int step = 1)
{
Stack stack = Stack();
for(int i = start; i <= end; i+=step)
{
stack.push(i);
}
return stack;
}
int main()
{
Stack s = createStackRange(0,5e6);
cout << s.peek() << endl;
sleep(1);
cout << "emptying" <<endl;
s.empty();
cout << "emptied" <<endl;
cout << "The size of the stack is " << s.getSize()<<endl;
cout << "waiting..." << endl;
sleep(10);
return 0;
}
How do you KNOW the memory isn't being released? The runtime library will manage allocations and may not release the memory back to the OS until the program terminates. If that's the case, the memory will be available for other allocations within your program during its execution.
However.... you seem to have other problems. My C++ is really rusty since I've been doing Java for 15 years, but in your Stack::Stack constructor you're allocating a Node instance on the system stack and then storing a reference to it in your "Stack". That Node instance goes out of scope when the constructor ends, leaving a dangling pointer.
Stack::Stack(int first)
{
Node first_top (first, NULL);
top = &first_top;
n = 1;
}
This is wrong , you cant assign address of a local object to class member( top ) , since local objects get destroyed when function returns.
Create a node on heap rather than stack , do something like this :
Stack::Stack(int first)
{
top = new Node(first, NULL);
n = 1;
}
And Make the concept of link list clear and use pen and paper if you can do so.
Your Stack::Push(int) operation seems buggy check it out what you have forget to do.
My suggestion is try to implement generic stack with the help of template ,so it will work for all data type .
When createStackRange() returns it'll return a copy of the Stack using the compiler-generated copy constructor which just makes a bitwise copy (i.e., it'll copy the pointer to the first node and the size.)
More seriously, you're missing the destructor for the Stack class. Ideally you'd have it walk the list and call delete on each Node. The Stack object created on the processor stack will automatically be cleaned up automatically when main() exits, but without a destructor, the nodes will still be allocated when the program ends. You probably want something like this for it:
Stack::~Stack()
{
while ( top )
{
Next *next = top->getNext();
delete top;
top = next;
}
}
The way to think of it is that the C++ compiler will automatically generate copy constructors and destructors for you, but they're normally shallow. If you need deep behavior you've got to do it implement it yourself somewhere.
After poring over the code, I couldn't find the leak so I compiled it and ran it in a debugger myself. I agree with Jim Garrision - I think you're seeing an artifact of the runtime rather than an actual leak, because I'm not seeing it on my side. The issues pointed out by NickLarsen and smith are both actual issues that you want to correct, but if you trace the code through, neither should actually be causing the problem you describe. The code smith singles out is never called in your example, and the code Nick singles out would cause other issues, but not the one you're seeing.
Creat a stub to test your code and user Memory Analysis tool like "Valgrind". This will find out memory leaks and corruptions for you.
check man-pages for more information.
Note that you should only roll your own stack for educational purposes. For any real code, you should use the stack implementation that comes with the C++ standard library...