CPP - using * or & to return address - c++

I am writing a code to make a linked list.
one of the function I wrote in order to make a linked list easier in the main function was[node is the name of a struct conatains a.data b.pointer name next) :
node& create_node(int value)
{
node newitem;
newitem.data=value;
newitem.next=NULL;
return (newitem);
};
When I write the function like this everything is ok but I want to write the function header as :
node * create_node(int value)
But when I write it that way and I write
return *newitem;
I get an error.
I wanted to ask why the VS shows me an error in the 2nd way and what is the difference between using * and & [I already read here about references but I don't understand why one should use it in functions as , from what I understood using references takes additional space and not contributing ] .
edit :thank you for help, when I posted this it was before I even ran a test on the main function only tried to avoid mistakes before compilation .
It took me some time but now I see the fundamental mistake I did .

If you want to return a pointer you should use a pointer:
node* create_node(int value)
{
node *newitem = new node;
newitem->data = value;
newitem->next = NULL;
return newitem;
};
Also please consider who'll delete the object then.

Your code returns a reference to a variable.
Unfortunately you return a reference to a local variable. This will fail, because the local variable will be destroyed uppont returning, but the caller will still try to reference it (that's UB) !
So if you want to return a reference, you shall make sure the object still exist:
node& create_node(int value) {
node* newitem = new node;
newitem->data=value;
newitem->next=NULL;
return (*newitem); // return the objet: this will be then be converted to a reference
}
You could also work with pointers as suggested by another answer. However in this case, I'd opt for shared_ptr:
shared_ptr<node> create_node(int value) {
node* newitem = new node;
newitem->data=value;
newitem->next=NULL;
return (shared_ptr<node>(newitem));
}

You should return &newitem.
But given the fact that your newitem is only available in this function's scope, the returned pointer will point to a destroyed object, so "nothing", or rather it will result in undefined behavior.
I guess you want your newitem to be created dynamically.
node * create_node(int value)
{
node * newitem = new node;
newitem->data=value;
newitem->next=NULL;
return newitem;
};

Related

Why Is My Binary Tree Overwriting The Leaves Of Its Root?

I've pinpointed my issue to this specific function, it's the helper function for my binary tree. Before this function call there is a node but instead of growing it seemingly just replaces that node. When I look at my code in my head it all makes sense but I can't figure out what I'm doing wrong.
Here is the function that calls add:
void BSTree::Insert(Client &newClient) {
if (isEmpty())
{
Node *newNode = new Node(newClient);
this->root = newNode;
}
else
add(this->root, newClient);
}
and here is my add() function:
BSTree::Node* BSTree::add(Node *node, Client &newClient) // helper function for Insert()
{
if (node == nullptr)
{
Node *newNode = new Node(newClient);
//node = newNode; // already tried adding this in
return newNode;
}
if (newClient.clientID < node->pClient->clientID)
return node->left = add(node->left, newClient); // already tried just returning add()
else
return node->right = add(node->right, newClient);
}
Since this is your question, I will explain what your code is doing. Imagine you have a mature binary tree already and you are adding a node to your tree. By the time you reach this line
return node->left = add(node->left, newClient);
Three separate instructions are carried out:
newClient is added to the left branch of node by add().
the left child of node is set to the return value of add().
the right hand side (RHS) of the assignment is returned by the parent function.
The issue is with number 2. If the tree you are adding to is mature already, changing left child of nodes as you're traversing the tree will cause the override effect that you're observing. In fact, the problem goes beyond overwriting leaves. Since you use the new keyword, the overwritten nodes still have allocated heap space, are never deleted and cause a memory leak.
Here are some thoughts to get you on the right direction:
Your insert() function ensures that the first time you call add(), you are not passing nullptr as the first argument. Take advantage of that and ensure nullptr is never passed into add() function by checking for nullptr before you do the recursive call. Change the return type of add() to void. You no longer need to check node is nullptr. Here's some pseudocode to guide you
void add(node, val)
if val < node.val
if node.left exists
add(node.left, val)
else
make a new object and set node.left to that object
else
if node.right exists
add(node.right, val)
else
make a new object and set node.right to that object
There is a problem with your logic. First of all, there is the insert() method which you should write like this for better understanding:
void BSTree::Insert(const Client &newClient) // use const to prevent modification
{
if (isEmpty()) { root = new Node(newClient); }
else { add(this->root, newClient); }
}
This way you are creating a new object at root directly with the help of 'root' pointer in BSTree.
Now, about the add() method. The 'node' you are passing as a parameter is a copy of the pointer variable, so the actual pointer value is not changed. See this:
BSTree::Node* BSTree::add(Node *node, Client &newClient) //logical error
You need to pass the Node* by reference like this using 'Node* &node':
BSTree::Node* BSTree::add(Node* &node, const Client &newClient)
Why is you binary tree overwriting the roots of its leaves? Answer:
Your recursive call with return statement is totally wrong.
return node->left = add(node->left, newClient);
The add(node->left, newClient) always returns the address of the leaves, and you are returning this value. It goes for recursive calls until it reaches the leaves place.
Conclusion: Since, there are a lot of bugs, I would suggest you re-write logic again carefully.
I hope this helps! :-)

Unique Pointer attempting to reference a deleted function

Hello I am trying to use pointers and learning the basics on unique pointers in C++. Below is my code I have commented the line of code in main function. to debug the problem However, I am unable to do so. What am I missing ? Is my move() in the insertNode() incorrect ? The error I get is below the code :
#include<memory>
#include<iostream>
struct node{
int data;
std::unique_ptr<node> next;
};
void print(std::unique_ptr<node>head){
while (head)
std::cout << head->data<<std::endl;
}
std::unique_ptr<node> insertNode(std::unique_ptr<node>head, int value){
node newNode;
newNode.data = value;
//head is empty
if (!head){
return std::make_unique<node>(newNode);
}
else{
//head points to an existing list
newNode.next = move(head->next);
return std::make_unique<node>(newNode);
}
}
auto main() -> int
{
//std::unique_ptr<node>head;
//for (int i = 1; i < 10; i++){
// //head = insertNode(head, i);
//}
}
ERROR
std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
Aside from other small problems, the main issue is this line:
return std::make_unique<node>(newNode);
You are trying to construct a unique pointer to a new node, passing newNode to the copy constructor of node. However, the copy constructor of node is deleted, since node contains a non-copyable type (i.e. std::unique_ptr<node>).
You should pass a std::move(newNode) instead, but this is problematic since you create the node on the stack and it will be destroyed at the exit from the function.
Using a std::unique_ptr here is a bad idea in my opinion, since, for example, to print the list (or insert into the list), you need to std::move the head (so you lose it) and so on. I think you're much better off with a std::shared_ptr.
I was having the same problem and indeed using a shared_ptr works.
Using the smart pointer as an argument in the function copies the pointer (not the data it points to), and this causes the unique_ptr to reset and delete the data it was previously pointing at- hence we get that "attempting to reference a deleted function" error. If you use a shared_ptr this will simply increment the reference count and de-increment it once you are out of the scope of that function.
The comments in the answers above suggest that using a shared_ptr is baseless. These answers were written before the C++17 standard and it is my understanding that we should be using the most updated versions of the language, hence the shared_ptr is appropriate here.
I don't know why we have to expose node type to user in any case. Whole thingamajig of C++ is to write more code in order to write less code later, as one of my tutors said.
We would like to encapsulate everything and leave no head or tail (pun intended) of node to user. Very simplistic interface would look like:
struct list
{
private:
struct node {
int data;
std::unique_ptr<node> next;
node(int data) : data{data}, next{nullptr} {}
};
std::unique_ptr<node> head;
public:
list() : head{nullptr} {};
void push(int data);
int pop();
~list(); // do we need this?
};
The implementation does something what Ben Voigt mentioned:
void list::push(int data)
{
auto temp{std::make_unique<node>(data)};
if(head)
{
temp->next = std::move(head);
head = std::move(temp);
} else
{
head = std::move(temp);
}
}
int list::pop()
{
if(head == nullptr) {
return 0; /* Return some default. */
/* Or do unthinkable things to user. Throw things at him or throw exception. */
}
auto temp = std::move(head);
head = std::move(temp->next);
return temp->data;
}
We actually need a destructor which would NOT be recursive if list will be really large. Our stack may explode because node's destructor would call unique_ptr's destructor then would call managed node's destructor, which would call unique_ptr's destructor... ad nauseatum.
void list::clear() { while(head) head = std::move(head->next); }
list::~list() { clear(); }
After that default destructor would ping unique_ptr destructor only once for head, no recursive iterations.
If we want to iterate through list without popping node, we'd use get() within some method designed to address that task.
Node *head = list.head.get();
/* ... */
head = head->next.get();
get() return raw pointer without breaking management.
How about this example, in addition to the sample code, he also mentioned some principles:
when you need to "assign" -- use std::move and when you need to just traverse, use get()

Recursive data structure in c++

I'm implementing a recursive data structure in c++ using classes. I'm having some trouble implementing it particularly with the "this" pointer.
In one function, I need to modify the "this" pointer. However that is not allowed. How do I do it? I read somewhere that you will need to pass "this" pointer to that function to change it. However I'm not clear with that. Does that behave like python's "self"? An example would be great
EDIT:
void insert(int key)
{
if (head == NULL)
{
/* I need to insert in beginning of structure */
List* tmp;
tmp->key = key;
tmp->next = this;
this = tmp; /* This does not work */
}
}
Thank You!
You cannot modify the this pointer, given that it behaves as if declared T* const. What you could do is hold a pointer to your own type inside of the class, and modify that.
class foo
{
/* ... */
private:
foo* p; // this can be modified
};
You cannot modify this, period. You need to re-structure your program so that you don't need to do that.
The best way to insert the way you're trying to is to create a double linked list, not a single one (with only the next pointer). In other words, you should have a previous pointer that points to the previous node in the list to properly insert using the this pointer. Else you need to insert from the parent node of the this.
ie with a double linked list:
Node* tmp = new Node;
tmp->key = key;
this->previous->next = tmp;
tmp->previous = this->previous;
tmp->next = this;
this->previous = tmp;
Edit:
Don't forget that "this" is ""simply"" a memory address so what you want to change is what's contained in it.

C++ function using reference as param error

struct node {
string info;
node *next;
node() {
info = "string";
next = NULL;
}
};
void insert(node &anode) {
node newNode;
anode.next = &newNode;
}
What is wrong with this implementation of insert for this structure ? How should I fix this?
added: Very sorry that I wasn't clear. I know what is wrong with the program. I want to know how I can insert a new node to a reference node. Since I am using a reference to a node as a param this mean that node must not be a pointer? So its stored on stack? which means I can't use memory from heap? (or else seg fault?) so how am I suppose to use new ? This is my main confusion. Perhaps my approach is wrong but I don't see why it should be.
What's wrong is that newNode lives in the scope of the insert function. You probably want something like
void insert(node &anode) {
node* newNode = new node;
anode.next = newNode;
}
but the parent node, or something else, then has to take care of the new node's lifetime. It now owns the next node. If you want the caller to be in charge, then this might be more suitable:
void insert(node& parentNode, node& nextNode) {
parentNode.next = &nextNode;
}
Note that you can avoid some of the lifetime issues by using boost::shared_ptr or std::shared_ptr if you have access to C++0x. These smart pointers basically wrap a pointer and take care to delete it when nobody is using it. The code would look something like this:
struct node {
// other data members...
shared_ptr<node> next;
// constructors/destructors
};
void insert(node& anode) {
anode.next = shared_ptr<node>(new node);
}
Now you don't have to worry about deleting the new node at any point.
You're returning (implicitly, as member of anode) a pointer to the local variable newNode. newNode is destroyed when you're leaving insert, so anode.next contains an invalid pointer afterwards.
BTW: should this question be tagged "homework"? :)
The "what's wrong" has nothing to do with references.
This implementation stores a pointer to a local variable in anode.next. Local variable gets destroyed immediately afterwards (when insert function exists), while the pointer continues to live pointing into a destroyed location.
The problem is that the local variable newNode will go out of scope once the function insert exists, and anode.next will now reference an invalid node.
Assuming that you are talking about a runtime error. The problem is that in your insert function
node newNode
is only a local variable, and it will be causing a problem when you try to access it later while iterating on the node(s).
Inside the insert function you should be doing something like this:
node* newNode = new node();
anode.next = newNode;
If you insist on using free functions, your best bet is probably something like:
static node* head = NULL;
static node* current = NULL;
void insert(std::string& val)
{
if (!head) {
current = new node(val);
head = current;
} else {
current->next = new node(val);
current = current->next;
}
}
and having your constructor accept an std::string as an argument. Relying on an entity outside the function to create nodes for you is probably not the best idea. You can pseudo-encapsulate that by creating nodes on demand when you call insert. Then you can run through the nodes using the head pointer and consequently delete them when you're finished with the list.
You are using a static address.
void insert(node &anode) {
node newNode;
anode.next = &newNode;
}
newNode is a local object. At the end of the function, it will go out of scope and its address will be invalid.

Passing a object by reference in c++

This is a noobie question, but I'm not sure how to pass by reference in C++. I have the following class which sets up a Node and a few functions.
class Node
{
public:
Node *next;
int data;
Node(int dat)
{
next = NULL;
data = dat;
}
Node* getNext()
{ return next; }
void setNext(Node *n)
{ next = n;}
void reverse(Node *root)
{
Node *previous = NULL;
while(root != NULL)
{
Node *next = root->getNext();
root->setNext(previous);
previous = root;
root = next;
}
root = previous;
}
};
Now, the purpose of my little class is to create a singularly linked list and have the ability to reverse it. And it seems to work fine, if I return the node named 'previous' at the end of reverse.
But look at my main function:
int main()
{
Node *root = new Node(1);
Node *num2 = new Node(2);
Node *num3 = new Node(3);
Node *num4 = new Node(4);
root->setNext(num2);
num2->setNext(num3);
num3->setNext(num4);
root->printList();
root->reverse(root);
root->printList();
return 0;
}
printList() was omitted for sake of space, but it just prints a list given a node. The problem is, when root->reverse(root) is called, root doesn't actually end up pointing to 'previous'.
The output would be this:
1
2
3
4
// the value of previous from the reverse function is 4
1
I really don't understand the output. Anyone care to explain what's happening? (Why isn't the list reversed even though if I did something like this root = root->reverse(root) where reverse returns previous, it would) why is it that root now only points to itself? I'm new to c++ and appreciate your help!
C++ has support for reference semantics. Therefore, for a given function:
void foo(Bar& bar);
To pass by reference you do:
int main() {
Bar whatsit;
foo(whatsit);
return 0;
}
That's it!
This is commonly confused with passing a pointer, where for a function such as:
void foo(Bar* bar);
You would do:
int main() {
Bar whatisit;
foo(&whatsit);
return 0;
}
The difference is mostly a matter of semantics:
- A reference is always valid. There is no reason to check for a NULL pointer.
- A pointer could be NULL, and as such, should be checked.
It is, however, possible for a reference to refer to a NULL pointer, however, if the programmer decides to be evil and abuse reference semantics, but the principle remains.
You aren't passing by reference. You are passing a copy of the pointer. This copy still points to the same node, but it is still just a copy with local scope. Basically it is another pointer pointing to the node that the pointer in main is pointing to (ha!). At the end of your function, your assignment is assigning previous to this pointer copy, and then the function ends and the copy goes out of scope. Your pointer in main remains unchanged.
The reason returning/assigning the pointer worked is that this copy which has been set to what you want is returned and assigned to your pointer in main.
You can fix this in a multitude of ways. Pass a reference to your pointer (ugly imo), use references, or return root and do an assignment.
To pass a pointer by reference you can declare reverse as:
void reverse(Node*& root) {
// ...
}