source: abuse/trunk/src/lisp/stack.h

Last change on this file was 561, checked in by Sam Hocevar, 12 years ago

lisp: fix a memory leak in the grow stack objets and refactor the class.

  • Property svn:keywords set to Id
File size: 1.3 KB
RevLine 
[56]1/*
[494]2 *  Abuse - dark 2D side-scrolling platform game
3 *  Copyright (c) 1995 Crack dot Com
4 *  Copyright (c) 2005-2011 Sam Hocevar <sam@hocevar.net>
[56]5 *
[494]6 *  This software was released into the Public Domain. As with most public
[555]7 *  domain software, no warranty is made or implied by Crack dot Com, by
8 *  Jonathan Clark, or by Sam Hocevar.
[56]9 */
10
[2]11#ifndef __STACK_HPP_
12#define __STACK_HPP_
[74]13
14#include <stdio.h>
[129]15#include <stdlib.h>
[74]16
17// A fixed-size stack class
[561]18template<class T> class GrowStack
[124]19{
[74]20public:
[561]21    GrowStack(int max_size)
22    {
23        m_max_size = max_size;
24        m_size = 0;
25        sdata = (T **)malloc(sizeof(T *) * m_max_size);
26    }
[2]27
[561]28    ~GrowStack()
[74]29    {
[561]30        if (m_size != 0)
31            fprintf(stderr, "warning: cleaning up nonempty stack\n");
32        free(sdata);
[74]33    }
34
[124]35    void push(T *data)
[74]36    {
[561]37        if (m_size >= m_max_size)
[74]38        {
[561]39            lbreak("error: stack overflow (%d >= %d)\n",
40                   (int)m_size, (int)m_max_size);
[74]41            exit(1);
42        }
[561]43        sdata[m_size] = data;
44        m_size++;
[74]45    }
[124]46
[561]47    T *pop(size_t total)
[74]48    {
[561]49        if (total > m_size)
[74]50        {
51            lbreak("error: stack underflow\n");
52            exit(1);
53        }
[561]54        m_size -= total;
55        return sdata[m_size];
[74]56    }
57
[561]58public:
59    T **sdata;
60    size_t m_size;
61
62private:
63    size_t m_max_size;
[74]64};
65
[2]66#endif
[561]67
Note: See TracBrowser for help on using the repository browser.