-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmemory.c
45 lines (40 loc) · 1.05 KB
/
memory.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
#include "clib.h"
// swaps two variables of any type
void swap(void *a, void *b, int size) {
unsigned char *buffer = safeMalloc(size);
memcpy(buffer, a, size);
memcpy(a, b, size);
memcpy(b, buffer, size);
free(buffer);
}
// allocates memory and checks whether this was successful
void *safeMalloc(int n) {
void *ptr = malloc(n);
if (ptr == NULL) {
printf("Error: malloc(%d) failed. "
"Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return ptr;
}
// allocates memory, initialized to 0, and
// checks whether this was successful
void *safeCalloc(int n, int size) {
void *ptr = calloc(n, size);
if (ptr == NULL) {
printf("Error: calloc(%d, %d) failed. "
"Out of memory?\n", n, size);
exit(EXIT_FAILURE);
}
return ptr;
}
// reallocates memory and checks if this was successful
void *safeRealloc(void *ptr, int newSize) {
ptr = realloc(ptr, newSize);
if (ptr == NULL) {
printf("Error: realloc(%d) failed. "
"Out of memory?\n", newSize);
exit(EXIT_FAILURE);
}
return ptr;
}