Here is my code
Node* Node::createNode(int n)
{
Node newNode(n);
Node *temp = &newNode;
return temp;
}
void Node::printNode(Node* node)
{
cout << node->data << "\t" << node->next << endl;
system("pause");
}
Here is the main function
int main(int argc, char* argv[])
{
Node *head = Node::createNode(10);
Node::printNode(head);
return 0;
}
Problem, I was expecting to print 10. Instead I get a garbage value of -858993460. I have noticed that until the point, parameter is passed into the function, it retains correct value. But inside the function printNode, the value changes. So I guess something is going wrong in the function call. Any help would be appreciated.
You’re returning a pointer to a local variable. When you later use that pointer in the main function, the variable it pointed to is long gone and you enter the realm of undefined behavior.
You could just return the node by value:
Or you could allocate one dynamically and return a smart pointer to it, enabling scope bound resource management (aka RAII):