util: add wrappers for memory allocation functions.

Add wrappers for malloc(), calloc(), realloc() and strdup() that check
if the allocation failed, print an error message and call exit(1). This
allows the caller to use the returned value without checking for errors.
master
Miroslav Lichvar 2015-08-28 17:06:30 +02:00 committed by Richard Cochran
parent 7b438defe5
commit e4325ee3fb
2 changed files with 89 additions and 0 deletions

52
util.c
View File

@ -368,6 +368,58 @@ int is_running(void)
return running;
}
void *xmalloc(size_t size)
{
void *r;
r = malloc(size);
if (!r) {
pr_err("failed to allocate memory");
exit(1);
}
return r;
}
void *xcalloc(size_t nmemb, size_t size)
{
void *r;
r = calloc(nmemb, size);
if (!r) {
pr_err("failed to allocate memory");
exit(1);
}
return r;
}
void *xrealloc(void *ptr, size_t size)
{
void *r;
r = realloc(ptr, size);
if (!r) {
pr_err("failed to allocate memory");
exit(1);
}
return r;
}
char *xstrdup(const char *s)
{
void *r;
r = strdup(s);
if (!r) {
pr_err("failed to allocate memory");
exit(1);
}
return r;
}
char *string_newf(const char *format, ...)
{
va_list ap;

37
util.h
View File

@ -254,6 +254,43 @@ int handle_term_signals(void);
*/
int is_running(void);
/**
* Allocate memory. This is a malloc() wrapper that terminates the process when
* the allocation fails.
*
* @param size Size of the block. Must be larger than 0.
* @return Pointer to the allocated memory.
*/
void *xmalloc(size_t size);
/**
* Allocate and clear an array. This is a calloc() wrapper that terminates the
* process when the allocation fails.
*
* @param nmemb Number of elements. Must be larger than 0.
* @param size Size of the element. Must be larger than 0.
* @return Pointer to the allocated memory.
*/
void *xcalloc(size_t nmemb, size_t size);
/**
* Reallocate memory. This is a realloc() wrapper that terminates the process
* when the allocation fails.
*
* @param size Size of the block. Must be larger than 0.
* @return Pointer to the allocated memory.
*/
void *xrealloc(void *ptr, size_t size);
/**
* Duplicate a string. This is a strdup() wrapper that terminates the process
* when the allocation fails.
*
* @param s String that should be duplicated.
* @return Pointer to the duplicated string.
*/
char *xstrdup(const char *s);
/**
* Get an allocated and formatted string. This is a wrapper around asprintf().
*