Fix snprintf in minimal-printf library.

mbed_minimal_putchar assumed that buffer being NULL meant that it
should print to a file. This caused a system crash when calling
snprintf with both buffer and stream set to NULL.
It is valid to call snprintf with a NULL buffer; nothing should
be outputted, but the string length should be measured.
pull/12632/head
Evelyne Donnaes 2020-03-23 13:46:12 +00:00
parent 532654ebb3
commit 94acb5da50
2 changed files with 17 additions and 10 deletions

View File

@ -635,6 +635,11 @@ static control_t test_snprintf_d(const size_t call_count)
TEST_ASSERT_EQUAL_INT(result_baseline, result_minimal);
#endif
int a = 2;
int b = 3;
result_minimal = mbed_snprintf(0, 0, "%d + %d = %d\n", a, b, a + b);
TEST_ASSERT_EQUAL_INT(10, result_minimal);
return CaseNext;
}

View File

@ -122,21 +122,23 @@ static void mbed_minimal_putchar(char *buffer, size_t length, int *result, char
{
/* only continue if 'result' doesn't overflow */
if ((*result >= 0) && (*result <= INT_MAX - 1)) {
if (buffer) {
/* write data only if there's enough space */
if ((size_t)*result < length) {
buffer[*result] = data;
}
/* increment 'result' even if data was not written. This ensures that
'mbed_minimal_formatted_string' returns the correct value. */
*result += 1;
} else {
if (stream) {
if (fputc(data, stream) == EOF) {
*result = EOF;
} else {
*result += 1;
}
} else {
if (buffer) {
/* write data only if there's enough space */
if ((size_t)*result < length) {
buffer[*result] = data;
}
}
/* increment 'result' even if data was not written. This ensures that
'mbed_minimal_formatted_string' returns the correct value. */
*result += 1;
}
}
}