From e6e077c8469f857ac58d804c788e887ce86e2303 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20Andr=C3=A9=20Tanner?= Date: Sun, 10 Jan 2016 12:23:32 +0100 Subject: text: introduce text_bytes_alloc0 utility function Heap allocates a zero terminated string of the given range. Freeing is the caller's responsibility. Checks for unsigned integer overflow i.e. passing SIZE_MAX as len will always fail because there is no room for the terminating NUL byte. This is important as EPOS is defined to be SIZE_MAX. --- text.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'text.c') diff --git a/text.c b/text.c index bf597da..93e79d6 100644 --- a/text.c +++ b/text.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -1441,6 +1442,17 @@ size_t text_bytes_get(Text *txt, size_t pos, size_t len, char *buf) { return len - rem; } +char *text_bytes_alloc0(Text *txt, size_t pos, size_t len) { + if (len == SIZE_MAX) + return NULL; + char *buf = malloc(len+1); + if (!buf) + return NULL; + len = text_bytes_get(txt, pos, len, buf); + buf[len] = '\0'; + return buf; +} + size_t text_size(Text *txt) { return txt->size; } -- cgit v1.2.3