c - Debian 中 gcc 的奇怪行为

标签 c linux gcc debian

char * stft (const char *fmt, ...) {

    va_list items;
    char *out;
    int magic = 0; // <-- here magic?

    va_start (items, fmt);
    vsprintf (out, fmt, items);
    va_end (items);

    return out;

}

像这样使用:

char *str = stft ("%s-%s %s", a, b, c);

这是可行的解决方案吗? 如果删除未使用的“魔术”变量 - 返回字符串后出现段错误。 做错了什么?

$ gcc --版本 gcc (Debian 4.4.5-8) 4.4.5

$ uname -a Linux deep-station (squeeze) 2.6.32-5-686 #1 SMP Fri May 10 08:33:48 UTC 2013 i686 GNU/Linux

最佳答案

您正在尝试写入未初始化的指针 out。这就是你崩溃的原因。这是严重未定义的行为。魔法是巧合;它不会使行为得到更好的定义。

可能最好使用 vsnprintf() :

char *out = malloc(256);
...
vsnprintf(out, 256, fmt, items);
...
return out;

或类似的东西。

您可以改进这一点。例如:

char *stft(const char *fmt, ...)
{
    va_list items;

    va_start(items, fmt);
    int length = vsnprintf(0, 0, fmt, items);
    va_end(items);
    char *out = malloc(length+1);
    if (out != 0)
    {
        va_start(items, fmt);
        vsnprintf(out, length+1, fmt, items);
        va_end(items);
    }

    return out;
}

确保在调用代码中释放分配的内存。

关于c - Debian 中 gcc 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23207587/

相关文章:

c - 'i' 上的操作可能未定义

c++ - 修复此编译错误 : identifier "and" is a special operator name in C++ [-Werror=c++-compat]?

c - 错误: Dereferencing pointer to incomplete type.

C,为结构数组内的字符串分配内存

c++ - 如果 malloc(STL 分配器等)请求分配 0 字节会发生什么

linux - 如何在远程计算机上执行 Perl 程序?

linux - Redhat Enterprise Linux 6 多播提要

linux - 如何根据文件的模式返回特定文本?

c++ - 为什么 gcc 会在全局命名空间中隐藏重载函数?

gcc - 在 C 代码 (GCC) 中定义一个程序段