C++: Run time error - Corruption of heap

Discussion in 'Software' started by heidigal83, Oct 7, 2010.

  1. heidigal83

    heidigal83

    Joined:
    Oct 7, 2010
    Messages:
    1
    Likes Received:
    0
    Hello,

    I am learning C++ and I just wrote the following problem and I am finding problem when "delete" statement at the end of the program is executed. If I comment out the last delete statement, the program works very fine - but, there will be a memory leak, as I have commented out the deallocation part.

    When the last "delete" statement is included, the program executes completely and then before closing, it pops up the run time error that there is a corruption of heap.

    Please advise me what is the cause of this problem. I have tried in all means to identify the problem and I am not able to!

    The code is:

    ----------------------------------------------------------
    #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;
    this->link = this + sizeof(node);
    }

    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 = new node;
    next = new node[5];

    head->create_node(10);
    cout << "Data 1 = " << head->get_data() << "\n";

    next = head->get_link();
    for(int i=1; i<4; i++)
    {
    next->create_node((i+1)*10);
    cout << "Data " << i+1 << " = " << next->get_data() << "\n";
    if(i<3)
    next = next->get_link();
    }

    delete head;
    //delete []next;

    system("pause");
    }
    ------------------------------------------------------------------

    Please help me in sorting out this problem.

    Thank you in advance.
    Kind regards,
    Hema
     
    heidigal83, Oct 7, 2010
    #1
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.