Add rreallocn() to librpmio public API

rreallocn() is like realloc() but with multiplication protection.
Inspired by glibc's reallocarray() but I dislike that name.

While at it, add xmallocn() as a shortcut to rreallocn(NULL, ...) case.

Based on initial patch by Demi Marie Obenour.
This commit is contained in:
Panu Matilainen 2022-02-08 09:23:58 +02:00 committed by Florian Festi
parent 1f03aba8b2
commit 6aec7c673f
3 changed files with 19 additions and 0 deletions

View File

@ -7,6 +7,7 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include "debug.h"
@ -58,6 +59,18 @@ void * rcalloc (size_t nmemb, size_t size)
return value;
}
void * rreallocn (void *ptr, size_t nmemb, size_t size)
{
register void *value = NULL;
if (size == 0) size++;
if (nmemb == 0) nmemb++;
if (nmemb < SIZE_MAX / size)
value = realloc(ptr, nmemb * size);
if (value == NULL)
value = vmefail(size);
return value;
}
void * rrealloc (void *ptr, size_t size)
{
register void *value;

View File

@ -124,6 +124,10 @@ void * rmalloc(size_t size);
RPM_GNUC_MALLOC RPM_GNUC_ALLOC_SIZE2(1,2)
void * rcalloc(size_t nmemb, size_t size);
/* Like realloc() but with overflow protection */
RPM_GNUC_MALLOC RPM_GNUC_ALLOC_SIZE2(2,3)
void * rreallocn(void * ptr, size_t nmemb, size_t size);
RPM_GNUC_ALLOC_SIZE(2)
void * rrealloc(void *ptr, size_t size);

View File

@ -64,8 +64,10 @@ extern int fdatasync(int fildes);
#include "rpmio/rpmutil.h"
/* compatibility macros to avoid a mass-renaming all over the codebase */
#define xmalloc(_size) rmalloc((_size))
#define xmallocn(_nmemb, _size) rreallocn(NULL, (_nmemb), (_size))
#define xcalloc(_nmemb, _size) rcalloc((_nmemb), (_size))
#define xrealloc(_ptr, _size) rrealloc((_ptr), (_size))
#define xreallocn(_ptr, _size) rreallocn((_ptr), (_nmemb), (_size))
#define xstrdup(_str) rstrdup((_str))
#define _free(_ptr) rfree((_ptr))