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

Last change on this file since 561 was 561, checked in by Sam Hocevar, 11 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
Line 
1/*
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>
5 *
6 *  This software was released into the Public Domain. As with most public
7 *  domain software, no warranty is made or implied by Crack dot Com, by
8 *  Jonathan Clark, or by Sam Hocevar.
9 */
10
11#ifndef __STACK_HPP_
12#define __STACK_HPP_
13
14#include <stdio.h>
15#include <stdlib.h>
16
17// A fixed-size stack class
18template<class T> class GrowStack
19{
20public:
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    }
27
28    ~GrowStack()
29    {
30        if (m_size != 0)
31            fprintf(stderr, "warning: cleaning up nonempty stack\n");
32        free(sdata);
33    }
34
35    void push(T *data)
36    {
37        if (m_size >= m_max_size)
38        {
39            lbreak("error: stack overflow (%d >= %d)\n",
40                   (int)m_size, (int)m_max_size);
41            exit(1);
42        }
43        sdata[m_size] = data;
44        m_size++;
45    }
46
47    T *pop(size_t total)
48    {
49        if (total > m_size)
50        {
51            lbreak("error: stack underflow\n");
52            exit(1);
53        }
54        m_size -= total;
55        return sdata[m_size];
56    }
57
58public:
59    T **sdata;
60    size_t m_size;
61
62private:
63    size_t m_max_size;
64};
65
66#endif
67
Note: See TracBrowser for help on using the repository browser.