mirror of https://github.com/ARMmbed/mbed-os.git
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
parent
532654ebb3
commit
94acb5da50
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue