File: mem.cpp

package info (click to toggle)
piler 0~20140707-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 364 kB
  • sloc: cpp: 5,369; makefile: 39
file content (53 lines) | stat: -rwxr-xr-x 1,062 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "piler2.h"

#ifdef	_MSC_VER
#include <crtdbg.h>
#endif

static int AllocatedBytes;
static int PeakAllocatedBytes;

// Allocate memory, fail on error, track total
void *allocmem(int bytes)
	{
	assert(bytes < 0xfffffff0);		// check for overlow
	char *p = (char *) malloc((size_t) (bytes + 4));
	if (0 == p)
		Quit("Out of memory (%d)", bytes);
	int *pSize = (int *) p;
	*pSize = bytes;
	AllocatedBytes += bytes;
	if (AllocatedBytes > PeakAllocatedBytes)
		PeakAllocatedBytes = AllocatedBytes;
	return p + 4;
	}

void freemem(void *p)
	{
	if (0 == p)
		return;
	int *pSize = (int *) ((char *) p - 4);
	int bytes = *pSize;
	assert(bytes <= AllocatedBytes);
	AllocatedBytes -= bytes;
	free(((char *) p) - 4);
	}

void chkmem()
	{
#ifdef	_MSC_VER
	assert(_CrtCheckMemory());
#endif
	}

void *reallocmem(void *p, int bytes)
	{
	if (0 == p)
		return allocmem(bytes);

	int *pSize = (int *) ((char *) p - 4);
	int oldbytes = *pSize;
	void *newp = allocmem(bytes);
	memcpy(newp, p, oldbytes);
	return newp;
	}