nasmlib: give gcc a bit more hints about how our allocation functions work

Tell gcc that our allocation functions are, indeed, allocation
functions, and that they don't ever return NULL.

Signed-off-by: H. Peter Anvin <hpa@zytor.com>
This commit is contained in:
H. Peter Anvin 2016-05-25 03:56:34 -07:00
parent 794688c21c
commit 4976cd2518
3 changed files with 34 additions and 7 deletions

View File

@ -177,6 +177,23 @@ char *strsep(char **, const char *);
# define unlikely(x) (!!(x))
#endif
/*
* Hints about malloc-like functions that never return NULL
*/
#if defined(__GNUC__) && __GNUC__ >= 4 /* ? */
# define never_null __attribute__((returns_nonnull))
# define safe_alloc never_null __attribute__((malloc))
# define safe_malloc(s) safe_alloc __attribute__((alloc_size(s)))
# define safe_malloc2(s1,s2) safe_alloc __attribute__((alloc_size(s1,s2)))
# define safe_realloc(s) never_null __attribute__((alloc_size(s)))
#else
# define never_null
# define safe_alloc
# define safe_malloc(s)
# define safe_malloc2(s1,s2)
# define safe_realloc(s)
#endif
/*
* How to tell the compiler that a function doesn't return
*/

View File

@ -145,12 +145,17 @@ static inline vefunc nasm_set_verror(vefunc ve)
* passed a NULL pointer; nasm_free will do nothing if it is passed
* a NULL pointer.
*/
void *nasm_malloc(size_t);
void *nasm_zalloc(size_t);
void *nasm_realloc(void *, size_t);
void * safe_malloc(1) nasm_malloc(size_t);
void * safe_malloc(1) nasm_zalloc(size_t);
void * safe_malloc2(1,2) nasm_calloc(size_t, size_t);
void * safe_realloc(2) nasm_realloc(void *, size_t);
void nasm_free(void *);
char *nasm_strdup(const char *);
char *nasm_strndup(const char *, size_t);
char * safe_alloc nasm_strdup(const char *);
char * safe_alloc nasm_strndup(const char *, size_t);
#define nasm_new(p) ((p) = nasm_zalloc(sizeof(*(p))))
#define nasm_newn(p,n) ((p) = nasm_calloc(sizeof(*(p)),(n)))
#define nasm_delete(p) do { nasm_free(p); (p) = NULL; } while (0)
/*
* Wrapper around fwrite() which fatal-errors on output failure.

View File

@ -108,14 +108,19 @@ void *nasm_malloc(size_t size)
return p;
}
void *nasm_zalloc(size_t size)
void *nasm_calloc(size_t size, size_t nelem)
{
void *p = calloc(size, 1);
void *p = calloc(size, nelem);
if (!p)
nasm_fatal(ERR_NOFILE, "out of memory");
return p;
}
void *nasm_zalloc(size_t size)
{
return nasm_calloc(size, 1);
}
void *nasm_realloc(void *q, size_t size)
{
void *p = q ? realloc(q, size) : malloc(size);