Skip to content

Commit dd0a0fc

Browse files
Merge pull request #4831 from fahhem/less_scanf
Remove excessive use of printf/scanf in mbed_fdopen/_open
2 parents 316c875 + 88f9078 commit dd0a0fc

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

platform/mbed_retarget.cpp

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -228,10 +228,10 @@ extern "C" FILEHANDLE PREFIX(_open)(const char* name, int openmode) {
228228

229229
FileHandle *res = NULL;
230230

231-
/* FILENAME: ":0x12345678" describes a FileHandle* */
231+
/* FILENAME: ":(pointer)" describes a FileHandle* */
232232
if (name[0] == ':') {
233233
void *p;
234-
std::sscanf(name, ":%p", &p);
234+
memcpy(&p, name + 1, sizeof(p));
235235
res = (FileHandle*)p;
236236

237237
/* FILENAME: "/file_system/file_name" */
@@ -826,8 +826,12 @@ void mbed_set_unbuffered_stream(std::FILE *_file) {
826826
*/
827827
std::FILE *mbed_fdopen(FileHandle *fh, const char *mode)
828828
{
829-
char buf[12]; /* :0x12345678 + null byte */
830-
std::sprintf(buf, ":%p", fh);
829+
// This is to avoid scanf(buf, ":%.4s", fh) and the bloat it brings.
830+
char buf[1 + sizeof(fh)]; /* :(pointer) */
831+
MBED_STATIC_ASSERT(sizeof(buf) == 5, "Pointers should be 4 bytes.");
832+
buf[0] = ':';
833+
memcpy(buf + 1, &fh, sizeof(fh));
834+
831835
std::FILE *stream = std::fopen(buf, mode);
832836
/* newlib-nano doesn't appear to ever call _isatty itself, so
833837
* happily fully buffers an interactive stream. Deal with that here.

0 commit comments

Comments
 (0)