-
Notifications
You must be signed in to change notification settings - Fork 0
/
537malloc.c
88 lines (81 loc) · 2.21 KB
/
537malloc.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
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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "537malloc.h"
#include "rangeTree.h"
void *malloc537(size_t size) {
void *address = NULL;
if ((int) size < 0) {
printf("Can't have a negative size.\n");
exit(-1);
} else if (size == 0) {
printf("Allocating a range of size of 0.\n");
}
// Is this a case?
if ((address = malloc(size)) == NULL && size > 0) {
printf("Unable to allocate memory.\n");
exit(-1);
}
if (size > 0) {
addRange(address, size);
}
return address;
}
void free537(void *ptr) {
int error;
error = freeRange(ptr);
switch (error) {
case -1:
printf("Attempting to free memory that was never allocated.\n");
exit(-1);
break;
case -2:
printf("Attempting to free memory that is not the first byte of its range.\n");
exit(-1);
break;
case -3:
printf("Attempting to free previously freed memory.\n");
exit(-1);
break;
case -4:
printf("Attempting to either free previously freed memory or free memory that is not the first byte of its range.\n");
exit(-1);
break;
}
// Free the actual memory
free(ptr);
}
void *realloc537(void *ptr, size_t size) {
void *address = NULL;
if (size == 0 && ptr != NULL) {
free537(ptr);
return NULL;
} else if (ptr == NULL) {
return malloc537(size);
}
if (rangeQuery(ptr, 1) == 1) {
freeRange(ptr);
}
if ((address = realloc(ptr, size)) == NULL && size > 0) {
printf("Unable to allocate memory!\n");
exit(-1);
}
if (size > 0) {
addRange(address, size);
}
return address;
}
void memcheck537(void *ptr, size_t size) {
int error = rangeQuery(ptr, size);
if (error == -1) {
printf("Memcheck: Desired address is not allocated.\n");
exit(-1);
} else if (error == -2) {
printf("Memcheck: Desired size falls outsides of bounds of range.\n");
exit(-1);
} else if (error == -3) {
printf("Memcheck: Desired address has been freed.\n");
exit(-1);
}
return;
}