-
Notifications
You must be signed in to change notification settings - Fork 0
/
memoryUtil.c
62 lines (42 loc) · 1.04 KB
/
memoryUtil.c
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
/*
* memoryUtil.c
*
*/
#include <stdlib.h>
#include <stdio.h>
#include "memoryUtil.h"
/*
* Amount of memory currently dynamically allocated.
*/
static
size_t sg_allocatedMemory;
size_t pollMemoryAllocated()
{
return sg_allocatedMemory;
} /* end of dynMemoryAllocated() */
void *safeMalloc(size_t size)
{
void *pMem = NULL;
if ((pMem = malloc(size)) == NULL) {
fprintf(stderr, "Error: safe_malloc() cannot allocate "
"memory of size %lu.\n", size);
exit(EXIT_FAILURE);
}
sg_allocatedMemory += size;
return pMem;
} /* end of safeMalloc() */
void *safeRealloc(void *pMem, size_t newSize, size_t extraMem)
{
if ((pMem = realloc(pMem, newSize)) == NULL) {
fprintf(stderr, "Error: safe_realloc() cannot allocate "
"new memory of size %lu.\n", newSize);
exit(EXIT_FAILURE);
}
sg_allocatedMemory += extraMem;
return pMem;
} /* end of safeRealloc() */
void safeFree(void *pMem, size_t memSize)
{
free(pMem);
sg_allocatedMemory = (sg_allocatedMemory <= memSize) ? 0 : (sg_allocatedMemory - memSize);
} /* end of safeFree() */