forked from blechschmidt/massdns
-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
security.h
81 lines (74 loc) · 1.64 KB
/
security.h
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
#ifndef INC_SECURITY
#define INC_SECURITY
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
/**
* Safely allocate memory on the heap by aborting on failure.
*
* @param n The size of the memory block.
* @return A pointer that points to the allocated block, NULL when requesting a block of zero bytes.
*/
void *safe_malloc(size_t n)
{
if(n == 0)
{
return NULL;
}
void *ptr = malloc(n);
// Check for successful allocation
if(ptr == NULL)
{
perror("Memory allocation failed");
abort();
}
return ptr;
}
void *safe_realloc(void *orig, size_t n)
{
void *ptr = realloc(orig, n);
// Check for successful allocation
if(ptr == NULL)
{
perror("Memory allocation failed");
abort();
}
return ptr;
}
/**
* Safely allocate memory on the heap and initialize it with zeroes by aborting on failure.
*
* @param n The size of the memory block.
* @return A pointer that points to the allocated block, NULL when requesting a block of zero bytes.
*/
void *safe_calloc(size_t n)
{
if(n == 0)
{
return NULL;
}
void *ptr = calloc(n, 1);
// Check for successful allocation
if(ptr == NULL)
{
perror("Memory allocation failed");
abort();
}
return ptr;
}
/**
* Safely free a memory allocation on the heap at the cost of a NULL assignment. Aims to prevent double free attacks.
*
* Example:
* char *x = malloc(10);
* safe_free(&x); // x == NULL
*
* @param ptr A pointer to a pointer that has been obtained using (safe_)malloc.
*/
void safe_free(void **ptr)
{
free(*ptr);
*ptr = NULL;
}
#endif