[common] fix gcc format-truncation false positive

This commit is contained in:
Geoffrey McRae 2021-02-22 01:39:28 +11:00
parent 28024de314
commit 99fc650550
2 changed files with 15 additions and 4 deletions

View File

@ -20,6 +20,10 @@ Place, Suite 330, Boston, MA 02111-1307 USA
#ifndef _H_LG_COMMON_STRINGUTILS
#define _H_LG_COMMON_STRINGUTILS
// vsprintf but with buffer allocation
int valloc_sprintf(char ** str, const char * format, va_list ap)
__attribute__ ((format (printf, 2, 0)));
// sprintf but with buffer allocation
int alloc_sprintf(char ** str, const char * format, ...)
__attribute__ ((format (printf, 2, 3)));

View File

@ -21,7 +21,7 @@ Place, Suite 330, Boston, MA 02111-1307 USA
#include <stdlib.h>
#include <stdarg.h>
static int valloc_sprintf(char ** str, const char * format, va_list ap)
int valloc_sprintf(char ** str, const char * format, va_list ap)
{
if (!str)
return -1;
@ -30,13 +30,20 @@ static int valloc_sprintf(char ** str, const char * format, va_list ap)
va_list ap1;
va_copy(ap1, ap);
int len = vsnprintf(NULL, 0, format, ap1);
// for some reason some versions of GCC warn about format being NULL when any
// kind of optimization is enabled, this is a false positive.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-truncation"
const int len = vsnprintf(*str, 0, format, ap1);
#pragma GCC diagnostic pop
va_end(ap1);
if (len < 0)
return len;
*str = malloc(len+1);
*str = malloc(len + 1);
int ret = vsnprintf(*str, len + 1, format, ap);
if (ret < 0)
@ -56,4 +63,4 @@ int alloc_sprintf(char ** str, const char * format, ...)
int ret = valloc_sprintf(str, format, ap);
va_end(ap);
return ret;
}
}