File: mem.c

package info (click to toggle)
mercury 0.9-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 18,488 kB
  • ctags: 9,800
  • sloc: objc: 146,680; ansic: 51,418; sh: 6,436; lisp: 1,567; cpp: 1,040; perl: 854; makefile: 450; asm: 232; awk: 203; exp: 32; fortran: 3; csh: 1
file content (103 lines) | stat: -rw-r--r-- 2,026 bytes parent folder | download
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
** Copyright (C) 1997 The University of Melbourne.
** This file may only be copied under the terms of the GNU Library General
** Public License - see the file COPYING.LIB in the Mercury distribution.
**
** $Id: mem.c,v 1.6 1997/07/27 14:59:28 fjh Exp $
*/

/* Imports */
#include	<stdlib.h>
#include	<stdio.h>
#include	<string.h>

#include	"util.h"
#include	"mem.h"

/* Exported definitions */

/* Local declarations */

static char
rcs_id[]	= "$Id: mem.c,v 1.6 1997/07/27 14:59:28 fjh Exp $";

/* 
 * Make sure the size of guard_bytes is a multiple of 8 to ensure we 
 * don't get unaligned accesses, even on 64-bit architectures.
 */
static const unsigned char
guard_bytes[] = {0xa5,0xa5,0xa5,0xa5,0xa5,0xa5,0xa5,0xa5};

/* Implementation */

void*
MB_malloc(size_t size)
{
	size_t		real_size;
	size_t		guard_size;
	unsigned char	*real_mem, *mem;

	guard_size = sizeof(guard_bytes) / sizeof(*guard_bytes);
	real_size = size + 2 * guard_size;
	
	real_mem = malloc(real_size);
	if (real_mem == NULL) {
		MB_fatal("mem.MB_alloc: malloc failed");
	}

	/* 
	 * Now check all allocated memory for corruption.
	 * XXX: Fill this in later...
	 */
	
	mem = real_mem + guard_size;
	return mem;
}

void
MB_free(void *mem)
{
	size_t		guard_size;
	unsigned char	*real_mem;

	/*
	 * Check that the memory to be freed was actually allocated.
	 * We can't check for still-remaining references to the
	 * memory without some sort of memory-marking as done in
	 * Hans Boehm's conservative garbage collector.
	 */

	/*
	 * Check all allocated memory for corruption.
	 * XXX: Do this later...
	 */

	guard_size = sizeof(guard_bytes) / sizeof(*guard_bytes);
	real_mem = (unsigned char *) mem - guard_size;
	free(real_mem);

	return;
}

void*
MB_realloc(void *mem, size_t size)
{

	void	*new_mem;

	/*
	 * Check all allocated memory for corruption.
	 * XXX: Do this later...
	 */

	new_mem = MB_malloc(size);
	memcpy(new_mem, mem, size);

	/*
	 * Check mem was actually allocated.
	 * XXX: Do later...
	 */
	MB_free(mem);

	return new_mem;
}