malloc failure causes exception in sprintf
When a floating-point format specifier is used with sprintf, one of sprintf's subroutines calls malloc. If malloc returns NULL, the subroutine attempts to write to address 0x00000004 at _dtoa_r+0x1C (looking through the source, it looks like multiple malloc calls are affected; the issue was discovered with newlib-nano but may also affect newlib). On the target processor, this memory is read-only, so the CPU jumps to the exception vector. Dereferencing invalid pointers can lead to undefined (or at least unexpected) behavior. If malloc fails, sprintf should return a value indicating that an error occurred.
Example program (requires a vector table to actually run it on the target):
/* Toolchain version: gcc-arm-
/* Compile options: arm-none-eabi-gcc -mcpu=cortex-m0 -mthumb -g -specs=nano.specs -u _printf_float sprintf_issue.c -o sprintf_issue.axf */
#include <stdio.h>
#include <errno.h>
void * _sbrk(ptrdiff_t nbytes)
{
/* Simulate out of memory condition (actual application had a real sbrk but ran out of heap space) */
errno = ENOMEM;
return (void *)-1;
}
void _exit(int status)
{
while(1) { }
}
int main()
{
char buf[32];
int result = sprintf(buf, "%f", 17.0 / 23.0);
return 0;
}
Question information
- Language:
- English Edit question
- Status:
- Answered
- Assignee:
- No assignee Edit question
- Last query:
- Last reply:
Can you help with this problem?
Provide an answer of your own, or ask Neil for more information if necessary.