c++ access violation writing exception on stack [closed] - c++

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 4 years ago.
Improve this question
I try to program an UPN Calculator in c++ with console input.
So I wrote a node and a stack class and use it in the main class. When starting everything goes well until I start pushing stuff on to the stack. I then get a "Access violation writing exception" and do not really understand what the problem is.
#include "pch.h"
#include "Node.h"
Node::Node(int value){this->value = value;}
int Node::GetValue(){return this->value;}
Node * Node::GetNode(){return this;}
Node* Node::GetNextNode(){return this->next_node;}
bool Node::SetNextNode(Node n)
{
this->next_node = &n;
return true;
}
Node * Node::GetBeforeNode(){return this->before_node;}
bool Node::SetBeforeNode(Node n)
{
this->before_node = &n; // <---- the error occures here
return true;
}

Don't create pointers to variables with local scopes.
Your Node n is passed to SetBeforeNode by value, so it's copied, you take it's address, but then n goes out of scope and you stay with dangling pointer, so instead of:
bool Node::SetBeforeNode(Node n)
it should be:
bool Node::SetBeforeNode(const Node& n)

Related

C++ - program crashes when defining custom destructor [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 5 years ago.
Improve this question
I have a class like this:
class Foo{
public:
Foo* next = nullptr;
Foo() = default;
Foo(Foo *next){
Foo::next = new Foo(*next);
}
Foo(const Foo &copy){
next = new Foo(*copy.next);
}
~Foo(){
delete next;
}
}
It compiles, but when I instantiate the class anywhere, the program crashes. When using a debugger a "breakpoint trap" is triggerd at delete next.
Why is that?
Edit:
The problem was, that there were instances where next could be set to pointers created outside of the class. I assumed you could delete pointers created anywhere.
Your pointer next is uninitialized, pointing to something unknown. delete will (most likely, if you are lucky) throw trying to delete it. Make sure the pointer points to memory allocated with new or is a nullptr.

Why did my C++mprogram stop working after being compiled? [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 6 years ago.
Improve this question
I'm a computer science student and have been coding with Java for the past year. Now I'm interested in learning C++. The first program that I wanted to code with C++ is an implementation of stack using linked list, which I have coded before using java. I pretty much have no idea what I'm doing and basically just writing what I thought was right until I got no compile error. So I finally did it, my program got no compile error, but when I ran it, a pop-up appeared saying that my 'Stack.exe has stopped working'
Here's my code:`
#include <iostream>
using namespace std;
class Stack;
class Node;
class Node
{
public:
string element;
Node *next;
Node(string, Node);
};
Node::Node(string element, Node next)
{
this -> element = element;
*(this -> next) = next;
}
class Stack
{
private:
Node *tos;
public:
Stack()
{
tos = NULL;
}
void push(string str)
{
tos = new Node(str, *tos);
}
string peek()
{
return tos->element;
}
string pop()
{
string temp = tos->element;
tos = (tos->next);
return temp;
}
};
int main(void)
{
Stack bob;
bob.push("Wow");
bob.push("Wiw");
cout << bob.peek();
return 0;
}
Can someone tell me what I did wrong? I did it like this because this was how I did it with Java.
Thank you :D
You're dereferencing null or undefined pointers in a couple places. First let's look at your Node constructor:
*(this -> next) = next;
Since next hasn't been defined yet, dereferencing it leads to undefined behavior. In practice, next will point to some random place in memory that you probably don't own, so writing to it will cause a program crash. Your Node constructor should take a pointer to Node as its second parameter instead of taking a Node by value:
Node::Node(string element, Node* next)
: element{element},
next{next}
{}
Note that I've also initialized Node's members instead of default-initializing them and then assigning to them in the constructor's body.
After fixing Node's constructor, you'll also need to fix Stack::push to pass a pointer instead of an object:
void push(string str)
{
tos = new Node(str, tos);
}
Note that even after fixing the crashing problem, you'll still leak memory when you pop from your Stack (or when a Stack is destroyed). You need to delete anything you new, or better yet use std::shared_ptr<Node> instead of raw Node*s.

Difficulty returning junks in my C++ stack implementation [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 have implemented a stack in C++, but I have a problem with returning junks.
For example, I have:
...
template<class T>
T stack<T>::pop()
{
/* Verific dacă există elemente pe stivă */
if( isEmpty() )
{
T junk;
fprintf(stderr, "No data.\n");
return junk;
}
...
}
This is not the right way for solving the problem, because I will have a valgrind error. How can I solve it?
This is poor idea because (among other things) if T's copy constructor can throw, it can destroy data (removes item from stack, then copying to return the item throws, which destroys the copy).
One way to fix the problem is to change the interface to something like this:
void stack<T>::pop(T &ret) {
if (!isempty())
ret = data[top--];
}
Or, to provide an indication of whether it succeeded:
bool stack<T>::pop(T &ret) {
if (isempty())
return false;
ret = data[top];
--top;
return true;
}
This way, if the copy constructor throws, top is never decremented, so the item remains on the stack. If execution gets past that, the rest of the function can't throw, so we always either succeed completely (the item is copied to the proper destination and removed from the stack) or else the function has no effect at all (the item remains on the stack).

[c++]Missing of destructor [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
when I declare a new queue object like that, the exe stop working:
arrayQueue myQueue;
myQueue.enqueue("111");
char* x=myQueue.dequeue();
cout<<x<<endl;
when I create the object using new, it works:
arrayQueue* myQueue=new arrayQueue();
myQueue->enqueue("111");
char* x=myQueue->dequeue();
cout<<x<<endl;
so what's the problem? the following code is a "queue" I wrote:
in .h head file:
class arrayQueue{
private:
array<char*,100> queueContrainer;
int maxSize;
int head;
int tail;
public:
arrayQueue();
~arrayQueue();
bool isEmpty();
bool isFull();
int getSize();
void enqueue(char*);
char* dequeue();
};
implementation in .cpp(only upload the constructor here:
arrayQueue::arrayQueue(){
head=0;
tail=0;
maxSize=100;
for(array<char*,100>::iterator it1=queueContrainer.begin();it1!=queueContrainer.end();++it1){
*it1="Empty";
}
}
main.cpp; arrayQueue.cpp; arrayQueue.h. three files to compile:
https://drive.google.com/file/d/0B5FCKG1I8ce0R1RORUFYWFhUN0E/edit?usp=sharing
https://drive.google.com/file/d/0B5FCKG1I8ce0QlBCTzdBUlJfZG8/edit?usp=sharing
https://drive.google.com/file/d/0B5FCKG1I8ce0SGdWOVg1RzNTNW8/edit?usp=sharing
Do you have a valid destructor? In the second example the object pointed to by myQueue is not deleted as it should, and the destructor never gets called.
In the first example myQueue is deleted when it goes out of scope, and the destructor will be called automatically. If your destructour is missing or buggy, the program will fail to compile or run.
In the first line
queue myQueue;
You are creating an object of type 'queue', possibly std::queue which has no 'enqueue' or 'dequeue' methods.

Why can't i print binary tree? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I created a class binary search tree.
but the problem is when i print the tree it crashes.
i think it can be an endless recursion in function print().
Here is my code
struct node{
node *l,*r;
int data;
};
class BinTree
{
private: node *root;
public:
BinTree(){ root=NULL; }
void add(int a){ add_node(a,root); };
void add_node(int a, node *rot)
{ node *curr; curr=rot;
if(curr==NULL)
{
curr=new node;
curr->data=a;
curr->l=NULL;
curr->r=NULL;
return;
}
if(a>=curr->data) curr=curr->r,add_node(a,curr);
if(a<curr->data) curr=curr->l,add_node(a,curr);
}
void print(){ inorder(root); }
void inorder(node *curr)
{
if(curr->l!=NULL) inorder(curr->l);
cout<<curr->data<<" ";
if(curr->r!=NULL) inorder(curr->r);
}
};
Can anyone help me?
In your add_node method, you never actually assign a value to the root. It should be something like this:
if(curr==NULL)
{
curr=new node;
curr->data=a;
curr->l=NULL;
curr->r=NULL;
root = curr;
return;
}
But, for the future, I have the same advice as Basile - use your compiler and your debugger to your advantange.
Your add_node is broken. If curr is NULL, it creates a new node but it never actually adds it to the existing tree. Thus all additions you make are effectively ignored and the tree stays empty.
The inorder function dereferences curr without checking whether it is NULL, and print calls it without checking whether root is NULL. Thus, your crash most likely is caused by tryin to print out an empty tree and then dereferencing a null pointer.
Learn how to use a debugger. Enable all warnings in the compiler.
On Linux, this means compile with g++ -Wall -g and debug with gdb