使用的sprintf没有手动分配的缓冲区 [英] Using sprintf without a manually allocated buffer
问题描述
在我工作的应用程序,日志工具利用的的sprintf
来格式化被写入到文件中的文本。那么,是这样的:
In the application that I am working on, the logging facility makes use of sprintf
to format the text that gets written to file. So, something like:
char buffer[512];
sprintf(buffer, ... );
这有时会导致问题时获取发送的消息变得太大手动分配的缓冲区。
This sometimes causes problems when the message that gets sent in becomes too big for the manually allocated buffer.
有没有办法让的sprintf
行为,无需手动分配内存这样吗?
Is there a way to get sprintf
behaviour without having to manually allocate memory like this?
编辑:在的sprintf
是C操作,我正在寻找C ++型解决方案(!如果有的话),我让这种行为..
while sprintf
is a C operation, I'm looking for C++ type solutions (if there are any!) for me to get this sort of behaviour...
推荐答案
没有你不能使用的sprintf()
来分配足够的内存。替代品包括:
No you can't use sprintf()
to allocate enough memory. Alternatives include:
- 使用
的snprintf()
来截断消息 - 没有完全解决您的问题,而是prevent的缓冲区溢出问题 - 双(或三或...)缓冲区 - 除非你是在一个约束的环境
- 使用C ++
的std ::字符串
和ostringstream
- 但是你将失去printf格式,你会必须使用的<&下;运营商 - 使用升压格式自带的一个类printf%运营商
- use
snprintf()
to truncate the message - does not fully resolve your problem, but prevent the buffer overflow issue - double (or triple or ...) the buffer - unless you're in a constrained environment
- use C++
std::string
andostringstream
- but you'll lose the printf format, you'll have to use the << operator - use Boost Format that comes with a printf-like % operator
这篇关于使用的sprintf没有手动分配的缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!