• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
LunarEffect

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

8 posts in this topic

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]
0

Share this post


Link to post
Share on other sites
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).
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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! =)
0

Share this post


Link to post
Share on other sites

#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.
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0