|
-
October 6th, 2010, 04:26 PM
#1
Memory related problem in C++ program
Hello,
I was just trying to implement a simple linked list in C++ using class.
The program is not complete. I am just building it. But facing problem in one of the function called "create_node".
--------------------------------------------------------------------------------------------------------------
#include <iostream>
#include <cstdlib>
using namespace std;
class node
{
int data;
node *link;
public:
node();
~node();
void create_node(int);
node* get_link();
int get_data();
};
node::node()
{
}
node::~node()
{
}
void node::create_node(int x)
{
this->data = x;
if(this->link == NULL)
this->link = new node;
this->link = this + 1;
}
node* node::get_link()
{
node temp;
temp.link = this->link;
return temp.link;
}
int node::get_data()
{
node temp;
temp.data = this->data;
return temp.data;
}
void main()
{
node *head, *next;
head = next = new node;
head->create_node(10);
cout << "Data 1 = " << head->get_data() << "\n";
next = head->get_link();
//next->create_node(20);
cout << "Data 2 = " << next->get_data() << "\n";
delete head;
delete next;
system("pause");
}
----------------------------------------------------------------------------------------------------
This program works fine if I do not call "create_node" function more than one time. When this function is called for the second time, I get "unhandled exception" error during execution. I am not sure if my implementation of "create_node" function is correct. But I guess this must be a memory related problem.
In create_node function, I am just trying to set the data to the value passed and increment the "link" pointer, so that it points to next node. I also allocate memory using "new", before I assign value to the "link" pointer.
Please let me know what is the problem in my "create_node" function?
Thank you in advance.
Kind regards,
Hema
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|