reentrant sprintf causes segmentation fault

Craig Howland
Fri May 3 17:18:00 GMT 2019

On 5/3/19 12:43 PM, David Lawrence wrote:
> Dear newlib maintainers and friends,
> I am having some trouble with newlib on a bare-metal embedded system
> that makes reentrant calls to sprintf. The reentrant call reliably
> experiences a segmentation fault. I have tested with both newlib 2.4.0
> and newlib 3.0.0, with both newlib-nano and regular newlib, to no
> effect.
> ...
> Do I have a fundamental misunderstanding of newlib's capability to
> support reentrant calls? Or does this seem like a legitimate bug? I
> would appreciate any suggestions for workarounds, and I would be happy
> to provide additional information or perform any further tests to
> assist the maintainers with this possible issue.
> Best regards,
> David Lawrence
      Reentrancy requires setup on your part, of which I see none in your 
supplied fragments.  Generate the manual and look at the reentrancy section.  
(You can also look at libc/reent/reent.tex, avoiding the need to make the manual 
but then being in source with formatting commands.)  It describes the 2 methods 
for handling it. In brief, you either need to directly call the reentrant forms 
of the functions with a per-thread structure, or you need to "context switch" by 
setting the global reentrancy pointer for each thread. (No, they do not need to 
be proper threads, but it gets the point across easily to use that term as an 
analogy.)  The second method is easier from the perspective of hiding reentrency 
from the main body of application code.  Both cases require you to define at 
least one of your own reentrancy structures in addition to the single default one.
      A simple technique I have used in an application quite like yours is to 
have the interrupt handler save _impure_ptr, overwrite it with the ISR's own, 
print, then restore _impure_ptr.

More information about the Newlib mailing list