Jump to content

  • Log In with Google      Sign In   
  • Create Account


My Linked List (Memory Leak question, C++)


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 LunarEffect   Members   -  Reputation: 122

Like
0Likes
Like

Posted 01 March 2009 - 06:06 PM

Hello Game-Dev'ers! I've just come back to C++ after a few years excursion into the Java world. Now I'm a bit rusty, and since C++ lacks a nice garbage collector, I was wondering about Memory Leaks. I know that for each "new" you need a "delete" and you are not supposed to lose pointers to dynamically allocated data, but I've just got into the concept of void pointers recently, which makes things a bit harder. Heres the code in question, do you think it would produce memory leaks?
//main.cpp
#include <iostream>
#include "LinkedList.h"
#include <string.h>

using namespace std;

int main()
{
    LinkedList ll;
    string data = "Bla";
    string data1 = "Bla1";
    string data2 = "Bla2";
    ll.add(&data);
    ll.add(&data1);
    ll.add(&data2);
    LLElement* temp = ll.first;
    while(temp != 0)
    {
        cout << *static_cast<string*>(temp->data) << "\n";
        temp = temp->next;
    }
    return 0;
}


//LinkedList.h
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
class LLElement{
    public:
    void* data;
    LLElement(void* data);
    LLElement* next;
    LLElement* previous;
};
class LinkedList
{
    public:
    ~LinkedList();
    LinkedList();
    void add(void* data);
    LLElement* first;
    LLElement* last;
};
#endif


//LinkedList.cpp
#include "LinkedList.h"

LinkedList::LinkedList()
{
    first=0;
    last=0;
}
LinkedList::~LinkedList()
{
    LLElement* element = first;
    while(element!=0){
        LLElement* temp = element;
        element=element->next;
        delete temp;
    }
}
void LinkedList::add(void* data)
{
    if(first == 0)
    {
        first = new LLElement(data);
        last = first;
    }
    else
    {
        LLElement* temp = new LLElement(data);
        last->next=temp;
        temp->previous=last;
        last=temp;
    }
}

/*
LLELEMENT SECTION!!!
*/
LLElement::LLElement(void* data)
{
    this->data=data;
    next = 0;
    previous = 0;
}

[Edited by - LunarEffect on March 2, 2009 1:27:09 AM]

Sponsor:

#2 scgames   Members   -  Reputation: 1973

Like
0Likes
Like

Posted 01 March 2009 - 06:26 PM

You can make your code more easily readable by using [source] tags (you can edit your original post using the 'edit' button in the upper-right).

#3 Black Knight   GDNet+   -  Reputation: 754

Like
0Likes
Like

Posted 01 March 2009 - 06:33 PM

Instead of using void* you can use template classes so that the linked list class will work for different types or you can just use the standard template library containers like std::list std::vector.
Using naked pointers have problems like dangling pointers and leaking if you forget to call delete.Using a shared_ptr will solve most of these problems.


#4 iMalc   Crossbones+   -  Reputation: 2287

Like
0Likes
Like

Posted 01 March 2009 - 07:05 PM

You don't appear to have any obvious leaks. However you're exposing the internals of the list publicly, so anything can touch its internals and do evil things to it, including causing leaks. Not necessarily on purpose of course, it's easy to write = where you intended to write ==, for example.
A real linked list class does not make it possible for external code to do things like point a node at it's predecessor creating a cycle, etc.
Of course at the same time this class doesn't actually do much yet. If you wanted to remove items, the owner of the list has to unlink the pointers by itself. A real class must provide such functionality.

I also advise that in your add function you separate out the creation of the node, from the placement of it into the list. The former able to of course be done in one place only, shortening your function somewhat.

You should also learn to use constructor initialisation lists.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

#5 LunarEffect   Members   -  Reputation: 122

Like
0Likes
Like

Posted 01 March 2009 - 07:36 PM

Thanks a lot guys, you've all been very helpful and I really appreciate it! =)

This whole linked list thing was more of a test of the possible applications of a void*. When I actually get round to programming something properly, I think I'll use the stl lists or use templates =)

Wow, I never heard of a constructor initialisation list. Can't remember any teachers of mine ever having mentioned them. Thanks a lot for the advice, I really like what they look like and I'm sure they will be very useful to me. =)

Again, thank you all very much, I've learned so much here! =)

#6 bradbobak   Members   -  Reputation: 1039

Like
0Likes
Like

Posted 01 March 2009 - 07:37 PM

Don't forget that if your string's go out of scope, the pointers will be bad.

#7 Zahlman   Moderators   -  Reputation: 1682

Like
0Likes
Like

Posted 02 March 2009 - 10:20 AM


#include <string.h>


This does not provide std::string. You simply happen to be getting it as a side effect of including iostream (not reliable). string.h provides C string manipulation functions, like strlen(), strncpy() etc. The C++ string class lives in <string> with no .h .

Also, you might want to study the design of the actual standard library containers, notably their public interfaces. :) Anyway, code like this would fail if the test code attempts to copy or assign an instance of a list. The copy would simply hold a copy of the 'first' and 'last' pointers (so changing the contents of one list changes the others, because they're sharing their contents), and then the destructor would eventually run for both lists; when the second one comes up for destruction, boom.

#8 NotAYakk   Members   -  Reputation: 876

Like
0Likes
Like

Posted 02 March 2009 - 05:00 PM

The rule of 3:
http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)
Constructors, Destructors and Copy Constructors tend to come in triplets.

If you define one, think long and hard why you haven't defined or disabled the others.

However, if you use reference-counting RAII pointers, you can go back to just defining constructors. And if your constructors merely exist to store non-pointer data, you similarly tend to have less issues.

Could I lead you down the rabbit hole?

#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>

Then change LLElement as follows:

boost::shared_ptr<LLElement> next;
boost::weak_ptr<LLElement> previous;

And LinkedList as follows:

boost::shared_ptr<LLElement> first;
boost::shared_ptr<LLElement> last;


And then make your code work. ;)

weak_ptrs can be created from shared_ptrs. You can get a shared_ptr from a weak_ptr by calling .lock() on the weak_ptr. weak_ptrs fail to produce a shared_ptr if the underlying data was destroyed before you call lock(). shared_ptrs are a reference-counting pointer (which is a weaker form of garbage collection, but also a much much cheaper one, than Java-style garbage collection).

The exercise might be fun to do. Include "printf-style" debugging to make sure that you aren't leaking a loop anywhere, and write & test a few methods like 'delete', 'insert', 'clone' and 'splice'. It would be a good exercise.


#9 LunarEffect   Members   -  Reputation: 122

Like
0Likes
Like

Posted 02 March 2009 - 05:22 PM

Again, thank you all so very much for your helpful replies =)
To be honest, I'm baffled about how many high-quality replies have been made here. I think I'll stick around here, perhaps I can help out with one thing or another =)
I've been wondering for a while what the boost library does, though I never bothered checking. Seems I missed out quite a bit.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS