[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[libmicrohttpd] [SSL-Example] load_file(), terminate c-string with a nul
From: |
Weber, Peter (Wilken Software Engineering GmbH) |
Subject: |
[libmicrohttpd] [SSL-Example] load_file(), terminate c-string with a null-character? |
Date: |
Wed, 24 Aug 2016 12:31:14 +0000 |
Hello!
I've used the example code from the PDF-Tutorial[1] and from the
website [2] to build the foundation for the application im currently
developing. Finally Valgrind reported an error "Invalid read of size 1"
(valgrind --leak-check=yes ./yourapplication).
Maybe I'm wrong. I think the returned C-String should be terminated by
the famous Null-Character, and therefore we also need to extend the
allocated buffer from the heap by one byte.
Original-Code:
-----------------------------------------------------------------------
static char *
load_file (const char *filename)
{
FILE *fp;
char *buffer;
long size;
size = get_file_size (filename);
if (size == 0)
return NULL;
fp = fopen (filename, "rb");
if (!fp)
return NULL;
buffer = malloc (size);
if (!buffer)
{
fclose (fp);
return NULL;
}
if (size != fread (buffer, 1, size, fp))
{
free (buffer);
buffer = NULL;
}
fclose (fp);
return buffer;
}
-----------------------------------------------------------------------
Patch:
-----------------------------------------------------------------------
--- load_file.c 2016-08-24 14:27:51.871565051 +0200
+++ new_load_file.c 2016-08-24 14:29:33.441565410 +0200
@@ -13,7 +13,7 @@
if (!fp)
return NULL;
- buffer = malloc (size);
+ buffer = malloc (size + 1);
if (!buffer)
{
fclose (fp);
@@ -26,6 +26,8 @@
buffer = NULL;
}
+ // null-termination of c-string
+ buffer[size] = '\0';
fclose (fp);
return buffer;
}
-----------------------------------------------------------------------
Thanks for your patience with me.
Peter
[1]https://www.gnu.org/software/libmicrohttpd/tutorial.pdf
[2]https://www.gnu.org/software/libmicrohttpd/tutorial.html#tlsauthenti
cation_002ec
- [libmicrohttpd] [SSL-Example] load_file(), terminate c-string with a null-character?,
Weber, Peter (Wilken Software Engineering GmbH) <=