cprintingprintf

Which print calls in C do NOT ever call malloc() under the hood?


I'm implementing my own fast_malloc() to replace malloc(). I need debugging prints inside it. Are there any print calls which are guaranteed to NOT ever call malloc(), or do I need to create my own, safe versions?

Previously, I had accidentally caused infinite recursion by having my malloc() call printf(), which then calls malloc(), which then calls printf()...forever.

If I need to create my own safe versions which use a fixed-size static array under the hood as the buffer to format into, that's all I need to know. I can do that.

How about puts() or putc()? They should be safe, no?

I'm on Linux Ubuntu 20.04. Ideally, whatever I do will be cross-platform-compliant, but I suppose I can customize if I need to for low-level system calls.


Related:

  1. Related, but not a duplicate since it is specific to snprintf(): snprintf that calls malloc, or snprintf that does not call malloc
  2. Does fprintf use malloc() under the hood?

Solution

  • Are there any print calls which are guaranteed to NOT ever call malloc()

    Usually you can call fprintf(stderr, ...). This is because stderr is unbuffered by default.

    However, this may not work from within malloc early in the process lifetime, before the rest of libc has initialized itself.

    Your best bet is to use write(2).