fprintf是否在后台使用malloc()? [英] Does fprintf use malloc() under the hood?

查看:187
本文介绍了fprintf是否在后台使用malloc()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个最小的o-damn-malloc-just-failed处理程序,该处理程序将一些信息写入文件(可能只是标准错误).我宁愿使用fprintf()而不是write(),但是如果fprintf()本身尝试进行malloc(),这将导致严重失败.

在C标准甚至glibc中是否有fprintf不会做到这一点的保证?

解决方案

不,不能保证不会.但是,我见过的大多数实现都倾向于使用固定大小的缓冲区来创建格式化的输出字符串(a).

就glibc(此处的资源)而言,有 调用了stdio-common/vfprintf.c中,printf家族的许多人都在较低端使用它,因此如果您是我,我不会依赖它.在设置了一些棘手的类似于FILE的字符串句柄后,甚至您可能认为不需要的字符串缓冲输出调用(如sprintf)似乎也可以解决该调用-请参见libio/iovsprintf.c.

我的建议是然后编写自己的代码以执行输出,以确保在后台不进行任何内存分配(当然,希望write本身不会这样做(与执行)).由于无论如何您都不会输出很多转换后的东西(可能只是"Dang, I done run outta memory!"),因此无论如何对格式化输出的需求还是值得怀疑的.


(a) C99环境方面的考虑表明(至少)某些早期实现具有缓冲限制.从我对Turbo C的记忆中,我认为4K就是极限,实际上,C99表示(在7.19.6.1 fprintf中):

任何一次转换可以产生的字符数至少应为 4095.

(C89的任务是整理现有做法,而不是创建新的语言,这就是为什么将其中一些最低限度的最大值放入标准的原因之一-它们被推广到该标准的后续版本中.) >

I want a minimal o-damn-malloc-just-failed handler, which writes some info to a file (probably just standard error). I would prefer to use fprintf() rather than write(), but this will fail badly if fprintf() itself tries to malloc().

Is there some guarantee, either in the C standard, or even just in glibc that fprintf won't do this?

解决方案

No, there's no guarantee that it won't. However, most implementations I've seen tend to use a fixed size buffer for creating the formatted output string (a).

In terms of glibc (source here), there are calls to malloc within stdio-common/vfprintf.c, which a lot of the printf family use at the lower end, so I wouldn't rely on it if I were you. Even the string-buffer output calls like sprintf, which you may think wouldn't need it, seem to resolve down to that call, after setting up some tricky FILE-like string handles - see libio/iovsprintf.c.

My advice is to then write your own code for doing the output so as to ensure no memory allocations are done under the hood (and hope, of course, that write itself doesn't do this (unlikelier than *printf doing it)). Since you're probably not going to be outputting much converted stuff anyway (probably just "Dang, I done run outta memory!"), the need for formatted output should be questionable anyway.


(a) The C99 environmental considerations gives an indication that (at least) some early implementations had a buffering limit. From my memory of the Turbo C stuff, I thought 4K was about the limit and indeed, C99 states (in 7.19.6.1 fprintf):

The number of characters that can be produced by any single conversion shall be at least 4095.

(the mandate for C89 was to codify existing practice, not create a new language, and that's one reason why some of these mimimum maxima were put in the standard - they were carried forward to later iterations of the standard).

这篇关于fprintf是否在后台使用malloc()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆