Problems with Linked List and pointers

  • Thread starter Thread starter rohanprabhu
  • Start date Start date
  • Tags Tags
    List Pointers
Click For Summary

Discussion Overview

The discussion revolves around issues encountered while implementing a linked list within a class in C++. Participants explore problems related to uninitialized pointers, memory management, and coding style, as well as providing suggestions for improvements and alternative approaches.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant points out that the member variables of the class are not initialized, which may lead to undefined behavior.
  • Another participant emphasizes the need for a constructor to initialize class variables properly to avoid crashes.
  • Concerns are raised about the use of a member variable for temporary storage in the additionalNode function, suggesting it should be a local variable instead.
  • Suggestions are made to use the C++ standard template library (STL) for linked list implementation instead of custom code.
  • A participant provides a revised version of the class, including a destructor that correctly deletes nodes, but notes a common error in accessing deleted memory.
  • Further modifications to the destructor are discussed to ensure proper memory management by advancing the pointer before deletion.
  • Clarifications are made regarding the naming of the 'polynomial' structure, with a participant suggesting it may be misleading as it represents a term rather than a full polynomial.

Areas of Agreement / Disagreement

Participants generally agree on the importance of initializing variables and managing memory correctly. However, there are differing opinions on the best practices for structuring the code and the appropriateness of using STL versus custom implementations.

Contextual Notes

Limitations include potential misunderstandings about memory management in C++ compared to other languages, as well as the implications of naming conventions in code readability.

Who May Find This Useful

Readers interested in C++ programming, particularly those working with data structures like linked lists, memory management, and coding best practices.

rohanprabhu
Messages
410
Reaction score
2
I've tried to implement a list within a class. I did this so that I can make 2 or more objects, where each object has a list as it's member. Here is the code to it:

Code:
struct coeffecient {
    int num;
    int den;
};

struct polynomial {
    float power;
    coeffecient coeff;
    int polarity;
};

/* Linked List definitions and implementation */

struct Node {
    polynomial info;
    Node *next;
};

class algebraList {
    public:
        Node *start, *newptr, *save, *ptr, *rear;
        
        void Insert_End(Node *np) {
            if(start == NULL) {
                start = rear = np;
            } else {
                rear->next = np;
                rear = np;
            }
        }
        
        void Display(Node *np) {
            while(np != NULL) {
                cout<<np->info.power<<" -> ";
                np = np->next;
            }
    
            cout<<"\n";
        }
        
        void additionalNode(polynomial x) {
            newptr = createNewNode(x);
            
            if(newptr != NULL) {
                cout<<"new node created..."; getch();
            } else {
                cout<<"error creating node.."; getch(); exit(1);
            }
        
            cout<<"inserting node in list..."; getch();
            Insert_End(newptr);
        }
        
        Node * createNewNode(polynomial n) {
            ptr = new Node;
            ptr->info = n;
            ptr->next = NULL;
            return ptr;
        }
};

And i accept data by:

Code:
polynomial x;

cout<<"\n Enter power for the new node: ";
cin>>x.power;
cout<<"creating new node.. "; getch();
        
listOne.additionalNode(x);

Whenever additionalNode is called, it shows 'Creating new node..', and 'new node created...' messages, as I've written in the additionalNode function [for error checking]. but, after that, when the program tries to run the Insert_End function, the program fives an error, 'The program has encountered a problem and needs to close' and closes.

Please help...
 
Technology news on Phys.org
I think maybe the problem is here:
Code:
              Node *start, *newptr, *save, *ptr, *rear;
for these data members are all haven't been initialized. I am not very sure whether in C++ they will be initialized, but in java they really will be.
So you'd better try it yourself for ensurence.

good luck!:-p
 
As shwx said, you have not initialized your data; you have instructed the computer that, when it creates an instance of class algebraList, it's allowed to fill in the variables start, newptr, save, ptr, and rear with whatever values it feels like using at the time. (And, luckily for you, the program decided to use some values that made your program crash, so that you know there is an error!) The same is true when you construct an instance of struct Node. You need to make a constructor for your classes that initialize all the variables properly.


Now, some style points...

The variable newptr has absolutely nothing to do with the structure of the list -- it's an implementation detail of the additionalNode function. Therefore, it should not be a member of the class, but instead a local variable of the function.

Your functions createNewNode and Display have nothing to do with individual instances of class algebraList; they should be declared static, or possibly changed to global functions.

(Incidentally, I would have expected the Display function to take no argument and display the linked list; why did you write it as you did?)

I count three different styles of method names and at least two different styles of type names; if possible, you should pick a single style and use it consistent.
 
Last edited:
Incidentally, if this isn't supposed an exercise in how to write linked lists, you would probably be better off using the C++ standard template library; the STL provides you with the class std::list which implements a doubly-linked list, the std::vector class which implements a resizable array, and several other container classes.
 
following your suggestions and critique from elsewhere, this is what I've finally arrived at:

Code:
class algebraList {
    List *start;
    List *end;
    
    public:    
    algebraList() {
        start = NULL;
        end = NULL;
    }
    
    ~algebraList() {
        List *nx = start;
        
        while(nx != NULL) {
            delete nx;
            nx = nx->next;
        }
    }        
    
    void addElement(polynomial *poly) {
        List *nx = new List;
        nx->info = *poly;
        nx->next = NULL;
        
        if(start == NULL) {
            start = end = nx;
        } else {
            end->next = nx;
            end = nx;
        }                
    }
    
    void displayList() {
        List *nx = start;
        
        while(nx != NULL) {
            cout<<nx->info.value<<endl;
            nx = nx->next;
        }
    }
};
 
It looks reasonable, except for one (common) error in that code:

Code:
 while(nx != NULL) {
            delete nx;
            nx = nx->next;
        }

Once you've deleted the object to which nx points, you shouldn't try to access it! You have no guarantee that that memory will still contain the data you want, or that the operating system will even allow you to access it! (fortunately or unfortunately, depeding on your POV, this code will usually do what you want. But really, you want to guarantee it does what you want!)

You need to advance nx before you delete the node. (Which means you will need to make a temporary copy of the pointer to the node you want to delete)



Oh, and another incidental comment: the structure you call 'polynomial' appears to be representing a 'monomial'. (Of course, every monomial is a polynomial, but the name might be misleading to someone else reading your code)
 
Last edited:
Hurkyl said:
Once you've deleted the object to which nx points, you shouldn't try to access it! You have no guarantee that that memory will still contain the data you want, or that the operating system will even allow you to access it! (fortunately or unfortunately, depeding on your POV, this code will usually do what you want. But really, you want to guarantee it does what you want!)

you were fast, but not as fast as the guys here: http://tinyurl.com/2mvdaf :p, nevermind, here is the code i modified:

Code:
~algebraList() {
    List *nx = start;
    List *np = NULL;
        
    do {
        np = nx->next;
        delete nx;
        nx = np;
    } while(np != NULL);
}

Oh, and another incidental comment: the structure you call 'polynomial' appears to be representing a 'monomial'. (Of course, every monomial is a polynomial, but the name might be misleading to someone else reading your code)

Actually, i did the current thing for only debugging purposes.. and in my real program too.. the structure 'polynomial' actually refers to a term of the polynomial only. so, the polynomials x^2, -2*x and 1 when added to an 'algebraList' will make: [itex]x^2 - 2x + 1[/itex]

Here is the actual structure of 'polynomial':

Code:
struct coeffecient {
    int num;
    int den;
};

struct polynomial {
    int power;
    coeffecient coeff;
    /* bool polarity; */
};

oh yeah.. and btw.. thanks a lot ;)
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
8K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K