Skip to content

Commit

Permalink
base: reallocarray
Browse files Browse the repository at this point in the history
  • Loading branch information
markokr committed Mar 11, 2015
1 parent 33de467 commit b1a4c37
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion m4/usual.m4
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ dnl AC_CHECK_FUNCS(basename dirname) # unstable, provide always
AC_CHECK_FUNCS(strlcpy strlcat memmem getpeereid sigaction sigqueue)
AC_CHECK_FUNCS(inet_ntop inet_pton poll getline memrchr regcomp)
AC_CHECK_FUNCS(err errx warn warnx getprogname setprogname)
AC_CHECK_FUNCS(posix_memalign memalign valloc explicit_bzero memset_s)
AC_CHECK_FUNCS(posix_memalign memalign valloc explicit_bzero memset_s reallocarray)
AC_CHECK_FUNCS(getopt getopt_long getopt_long_only)
AC_CHECK_FUNCS(fls flsl flsll ffs ffsl ffsll)
AC_CHECK_FUNCS(fnmatch mbsnrtowcs nl_langinfo strtod_l)
Expand Down
9 changes: 9 additions & 0 deletions test/test_base.c
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,18 @@ static void test_misc(void *_p)
end:;
}

static void test_reallocarray(void *_p)
{
void *p;
p = reallocarray(NULL, 1, 1); tt_assert(p); free(p);
p = reallocarray(NULL, LLONG_MAX, LLONG_MAX); tt_assert(p == NULL);
end:;
}

struct testcase_t base_tests[] = {
{ "ptr", test_ptr },
{ "misc", test_misc },
{ "reallocarray", test_reallocarray },
END_OF_TESTCASES
};

15 changes: 15 additions & 0 deletions usual/base.c
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
*/

#include <usual/base.h>
#include <usual/bits.h>

#if defined(HAVE_MALLOC_H) && defined(__darwin__)
#include <malloc.h>
Expand Down Expand Up @@ -51,3 +52,17 @@ int posix_memalign(void **ptr_p, size_t align, size_t len)
}
#endif

#ifndef HAVE_REALLOCARRAY

void *reallocarray(void *p, size_t count, size_t size)
{
size_t total;
if (!safe_mul_size(&total, count, size)) {
errno = ENOMEM;
return NULL;
}
return realloc(p, total);
}

#endif

10 changes: 10 additions & 0 deletions usual/base.h
Original file line number Diff line number Diff line change
Expand Up @@ -324,5 +324,15 @@ static inline void *zmalloc(size_t len)
int posix_memalign(void **ptr_p, size_t align, size_t len);
#endif

#ifndef HAVE_REALLOCARRAY
#define reallocarray(a,b,c) usual_reallocarray(a,b,c)

/**
* Same as realloc(), but safely calculates total size.
*/
void *reallocarray(void *p, size_t count, size_t size);

#endif

#endif

0 comments on commit b1a4c37

Please sign in to comment.