aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/libmdsserver/macros.h14
-rw-r--r--src/mds-kbdc.c17
2 files changed, 26 insertions, 5 deletions
diff --git a/src/libmdsserver/macros.h b/src/libmdsserver/macros.h
index 481d281..79d427f 100644
--- a/src/libmdsserver/macros.h
+++ b/src/libmdsserver/macros.h
@@ -331,6 +331,20 @@
/**
+ * `xremalloc` that stores the old variable
+ *
+ * @param old:type* The variable to which to store with the old variable that needs
+ * to be `free`:ed on failure, and set to `NULL` on success.
+ * @param var:type* The variable to which to assign the reallocation
+ * @param elements:size_t The number of elements to allocate
+ * @param type The data type of the elements for which to create an allocation
+ * @return :int Evaluates to true if an only if the allocation failed
+ */
+#define xxrealloc(old, var, elements, type) \
+ (old = var, (xrealloc(var, elements, type) ? 1 : (old = NULL, 0)))
+
+
+/**
* Double to the size of an allocation on the heap
*
* @param old:type* Variable in which to store the old value temporarily
diff --git a/src/mds-kbdc.c b/src/mds-kbdc.c
index 3dcb542..eae5348 100644
--- a/src/mds-kbdc.c
+++ b/src/mds-kbdc.c
@@ -69,9 +69,7 @@ static char* read_file(const char* restrict pathname, size_t* restrict size)
/* Make sure the buffer is not small. */
if (buf_size - buf_ptr < 2048)
{
- old = content;
- fail_if (xrealloc(content, buf_size <<= 1, char));
- old = NULL;
+ fail_if (xxrealloc(old, content, buf_size <<= 1, char));
}
/* Read a chunk of the file. */
got = read(fd, content + buf_ptr, (buf_size - buf_ptr) * sizeof(char));
@@ -82,7 +80,7 @@ static char* read_file(const char* restrict pathname, size_t* restrict size)
}
/* Shrink the buffer so it is not excessively large. */
- fail_if (xrealloc(content, buf_ptr, char));
+ fail_if (xxrealloc(old, content, buf_ptr, char));
/* Close file decriptor for the file. */
close(fd);
@@ -154,6 +152,7 @@ int main(int argc_, char** argv_)
const char* pathname = argv_[1];
char* restrict content = NULL;
char* restrict real_content = NULL;
+ char* restrict old = NULL;
size_t content_size;
size_t real_content_size;
@@ -164,17 +163,25 @@ int main(int argc_, char** argv_)
content = read_file(pathname, &content_size);
fail_if (content == NULL);
+ /* Make sure the content ends with a new line. */
+ if (!content_size || (content[content_size - 1] != '\n'))
+ {
+ fail_if (xxrealloc(old, content, content_size + 1, char));
+ content[content_size++] = '\n';
+ }
+
/* Simplify file. */
fail_if (xmalloc(real_content, content_size, char));
memcpy(real_content, content, content_size * sizeof(char));
real_content_size = content_size;
content_size = remove_comments(content, content_size);
- fail_if (xrealloc(content, content_size, char));
+ fail_if (xxrealloc(old, content, content_size, char));
return 0;
pfail:
xperror(*argv);
+ free(old);
free(content);
free(real_content);
return 1;