From 1fe2fa08d37090fff67edd444dadacd11ff8eebf Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Fri, 20 Nov 2015 16:52:34 +1030 Subject: [PATCH] noerr: add free_noerr(). Signed-off-by: Rusty Russell --- ccan/noerr/noerr.c | 8 ++++++++ ccan/noerr/noerr.h | 8 ++++++++ ccan/noerr/test/run.c | 6 +++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/ccan/noerr/noerr.c b/ccan/noerr/noerr.c index 4368a5e7..972f3074 100644 --- a/ccan/noerr/noerr.c +++ b/ccan/noerr/noerr.c @@ -2,6 +2,7 @@ #include "noerr.h" #include #include +#include int close_noerr(int fd) { @@ -41,3 +42,10 @@ int unlink_noerr(const char *pathname) errno = saved_errno; return ret; } + +void free_noerr(void *p) +{ + int saved_errno = errno; + free(p); + errno = saved_errno; +} diff --git a/ccan/noerr/noerr.h b/ccan/noerr/noerr.h index 99b0f690..bafb59bd 100644 --- a/ccan/noerr/noerr.h +++ b/ccan/noerr/noerr.h @@ -30,4 +30,12 @@ int fclose_noerr(FILE *fp); */ int unlink_noerr(const char *pathname); +/** + * free_noerr - free memory without stomping errno. + * @p: the pointer to free. + * + * errno is saved and restored across the call to free: the standard leaves + * that undefined. + */ +void free_noerr(void *p); #endif /* NOERR_H */ diff --git a/ccan/noerr/test/run.c b/ccan/noerr/test/run.c index d5d48584..48086a24 100644 --- a/ccan/noerr/test/run.c +++ b/ccan/noerr/test/run.c @@ -13,7 +13,7 @@ int main(int argc, char *argv[]) int fd; FILE *fp; - plan_tests(15); + plan_tests(16); /* Should fail to unlink. */ ok1(unlink(name) != 0); ok1(errno == ENOENT); @@ -59,5 +59,9 @@ int main(int argc, char *argv[]) ok1(errno == 100); unlink(name); + errno = 101; + free_noerr(malloc(7)); + ok1(errno == 101); + return exit_status(); } -- 2.39.2