mirror of
https://gitlab.com/80486DX2-66/gists
synced 2024-11-15 14:55:55 +05:30
66 lines
2.5 KiB
C
66 lines
2.5 KiB
C
|
/*
|
||
|
* safe_mem.h
|
||
|
*
|
||
|
* A header-only library (macro collection) for safer memory management.
|
||
|
*
|
||
|
* Author: Intel A80486DX2-66
|
||
|
* License: Creative Commons Zero 1.0 Universal
|
||
|
*/
|
||
|
|
||
|
#ifndef _SAFE_MEM_H
|
||
|
#define _SAFE_MEM_H
|
||
|
|
||
|
#include <stdlib.h>
|
||
|
|
||
|
#define SAFE_FREE_ERROR_HOOK /* user-defined */
|
||
|
|
||
|
#define safe_free(ptr) do { \
|
||
|
/* prevents NULL-freeing and double freeing */ \
|
||
|
if (ptr != NULL) { \
|
||
|
free(ptr); \
|
||
|
ptr = NULL; \
|
||
|
} else { SAFE_FREE_ERROR_HOOK; } \
|
||
|
} while (0)
|
||
|
|
||
|
#define precise_malloc(nmemb, size) \
|
||
|
/* prevents incorrect casting */ \
|
||
|
malloc((size_t) nmemb * (size_t) size)
|
||
|
|
||
|
/* secure_erase(dest, count): erases memory explicitly */
|
||
|
#if defined(__FreeBSD__)
|
||
|
# define NO_SECURE_ERASE_WARRANTY 0
|
||
|
# define SECURE_ERASE_WARRANTY "OpenBSD/FreeBSD: explicit_bzero"
|
||
|
|
||
|
# include <strings.h>
|
||
|
# define secure_erase explicit_bzero
|
||
|
#elif defined(_WIN32)
|
||
|
# define NO_SECURE_ERASE_WARRANTY 0
|
||
|
# define SECURE_ERASE_WARRANTY "Microsoft Windows: SecureZeroMemory"
|
||
|
|
||
|
# include <windows.h>
|
||
|
# define secure_erase SecureZeroMemory
|
||
|
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
|
||
|
# define NO_SECURE_ERASE_WARRANTY 0
|
||
|
# define SECURE_ERASE_WARRANTY "C11+: memset_s"
|
||
|
|
||
|
# define secure_erase(dest, count) memset_s(dest, count, 0, count)
|
||
|
#else
|
||
|
# define NO_SECURE_ERASE_WARRANTY 1
|
||
|
|
||
|
# define __observe__(ptr) do { \
|
||
|
if (*ptr == 0) { \
|
||
|
++(*ptr); \
|
||
|
fprintf(stderr, ""); \
|
||
|
} else \
|
||
|
--(*ptr); \
|
||
|
} while (0)
|
||
|
|
||
|
# define secure_erase(dest, count) do { \
|
||
|
memset(dest, 0, count); \
|
||
|
for (size_t i = 0; i < count; i++) \
|
||
|
__observe__(dest[i]); \
|
||
|
} while (0)
|
||
|
#endif
|
||
|
|
||
|
#endif /* _SAFE_MEM_H */
|