Skip to content

Commit bde5620

Browse files
committed
Do not use the stack for large printfs
Can cause a stack overflow.
1 parent 0a3c299 commit bde5620

File tree

1 file changed

+26
-10
lines changed

1 file changed

+26
-10
lines changed

examples/stdlib.c

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4147,19 +4147,30 @@ static int asprintf(char **strp, const char *format, ...)
41474147
return result;
41484148
}
41494149

4150+
#define PRINTF_BUF_ALLOC(buf, size) \
4151+
char buf_0[((size) <= BUFSIZ? result: 0)], \
4152+
*buf = (size <= BUFSIZ? buf_0: (char *)malloc(size))
4153+
#define PRINT_BUF_FREE(buf) \
4154+
if (buf != buf_0) free(buf)
4155+
41504156
static int vfprintf(FILE *stream, const char *format, va_list ap)
41514157
{
41524158
va_list aq;
41534159
va_copy(aq, ap);
41544160
int result = vsnprintf(NULL, SIZE_MAX, format, ap);
41554161
if (result >= 0)
41564162
{
4157-
char buf[result+1];
4158-
result = vsnprintf(buf, result+1, format, aq);
4159-
if (result >= 0)
4163+
ssize_t size = result+1;
4164+
PRINTF_BUF_ALLOC(buf, size);
4165+
if (buf != NULL)
41604166
{
4161-
if (fputs(buf, stream))
4162-
result = -1;
4167+
result = vsnprintf(buf, size, format, aq);
4168+
if (result >= 0)
4169+
{
4170+
if (fputs(buf, stream))
4171+
result = -1;
4172+
}
4173+
PRINT_BUF_FREE(buf);
41634174
}
41644175
}
41654176
va_end(aq);
@@ -4173,12 +4184,17 @@ static int vfprintf_unlocked(FILE *stream, const char *format, va_list ap)
41734184
int result = vsnprintf(NULL, SIZE_MAX, format, ap);
41744185
if (result >= 0)
41754186
{
4176-
char buf[result+1];
4177-
result = vsnprintf(buf, result+1, format, aq);
4178-
if (result >= 0)
4187+
ssize_t size = result+1;
4188+
PRINTF_BUF_ALLOC(buf, size);
4189+
if (buf != NULL)
41794190
{
4180-
if (fputs_unlocked(buf, stream))
4181-
result = -1;
4191+
result = vsnprintf(buf, result+1, format, aq);
4192+
if (result >= 0)
4193+
{
4194+
if (fputs_unlocked(buf, stream))
4195+
result = -1;
4196+
}
4197+
PRINT_BUF_FREE(buf);
41824198
}
41834199
}
41844200
va_end(aq);

0 commit comments

Comments
 (0)