Skip to content

Commit 94acb5d

Browse files
committed
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.
1 parent 532654e commit 94acb5d

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

TESTS/mbed_platform/minimal-printf/compliance/main.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,11 @@ static control_t test_snprintf_d(const size_t call_count)
635635
TEST_ASSERT_EQUAL_INT(result_baseline, result_minimal);
636636
#endif
637637

638+
int a = 2;
639+
int b = 3;
640+
result_minimal = mbed_snprintf(0, 0, "%d + %d = %d\n", a, b, a + b);
641+
TEST_ASSERT_EQUAL_INT(10, result_minimal);
642+
638643
return CaseNext;
639644
}
640645

platform/source/minimal-printf/mbed_printf_implementation.c

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -122,21 +122,23 @@ static void mbed_minimal_putchar(char *buffer, size_t length, int *result, char
122122
{
123123
/* only continue if 'result' doesn't overflow */
124124
if ((*result >= 0) && (*result <= INT_MAX - 1)) {
125-
if (buffer) {
126-
/* write data only if there's enough space */
127-
if ((size_t)*result < length) {
128-
buffer[*result] = data;
129-
}
130-
131-
/* increment 'result' even if data was not written. This ensures that
132-
'mbed_minimal_formatted_string' returns the correct value. */
133-
*result += 1;
134-
} else {
125+
if (stream) {
135126
if (fputc(data, stream) == EOF) {
136127
*result = EOF;
137128
} else {
138129
*result += 1;
139130
}
131+
} else {
132+
if (buffer) {
133+
/* write data only if there's enough space */
134+
if ((size_t)*result < length) {
135+
buffer[*result] = data;
136+
}
137+
}
138+
139+
/* increment 'result' even if data was not written. This ensures that
140+
'mbed_minimal_formatted_string' returns the correct value. */
141+
*result += 1;
140142
}
141143
}
142144
}

0 commit comments

Comments
 (0)