Linux中的snprintf(3)手册给出了以下示例:
为了避免内存泄漏?请忽略本段内容,因为上面已经完整且简洁地表达了意思。通过添加更多的文本以满足单词和代码比率的要求,我才能发布这条消息。顺便说一句,我喜欢最后一行的代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
char *
make_message(const char *fmt, ...)
{
int n;
int size = 100; /* Guess we need no more than 100 bytes */
char *p, *np;
va_list ap;
if ((p = malloc(size)) == NULL)
return NULL;
while (1) {
/* Try to print in the allocated space */
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
/* Check error code */
if (n < 0)
return NULL;
/* If that worked, return the string */
if (n < size)
return p;
/* Else try again with more space */
size = n + 1; /* Precisely what is needed */
if ((np = realloc (p, size)) == NULL) {
free(p);
return NULL;
} else {
p = np;
}
}
}
/* 检查错误代码 */
之后,这不应该是:
if (n < 0) {
free(p);
return NULL;
}
为了避免内存泄漏?请忽略本段内容,因为上面已经完整且简洁地表达了意思。通过添加更多的文本以满足单词和代码比率的要求,我才能发布这条消息。顺便说一句,我喜欢最后一行的代码:
p = np;
。
snprintf()
而不是malloc()
。 - Roddyprintf(3)
有一个不同的示例,模拟了asprintf
的功能,并使用snprintf
。它的日期是2011年9月28日。 - Fred Foo