c - snprintf 手册页示例内存泄漏?

标签 c linux printf manpage

snprintf(3) 的 Linux 手册页给出了以下示例:

#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;

最佳答案

是的,这段代码有漏洞。

vsnprintf 可以在出错时返回负数。 在 VC++ 中,当目标缓冲区太小时,vsnprintf 返回 -1,这打破了这段代码中的逻辑...... 看这里: MSDN VC 实现不符合 C 标准...

vsnprintf 失败的其他来源是发送 NULL“格式”缓冲区或格式缓冲区中的错误编码。

关于c - snprintf 手册页示例内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19933479/

相关文章:

c - 在 Windows 上将 SQLite 与 C 结合使用

c - 从时间戳中提取时间

linux - 没有 bash 运行时权限被拒绝

c - 格式字符串周围的 `TEXT` 在 "printf"中是什么意思

c - 非常简单的 C 字符串 : Storing and printing a string in a struct in C

perl - 在sprintf中截断(不舍入)小数位?

c - 如何用C语言将单个位写入文件

c - 除了调用 free() 之外,有没有办法确定指针是否可以传递给 free()?

linux - 如何在Linux终端中动态显示结果?像 'top' 命令

linux - 保留备份