简体   繁体   English

gcc在Debian中的奇怪行为

[英]Strange behaviour of gcc in 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;

}

Use like: 使用方式如下:

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

This is working solution? 这是可行的解决方案吗? if delete unused "magic" variable - I have Segmentation fault after return string. 如果删除未使用的“魔术”变量-返回字符串后出现分段错误。 What doing wrong? 怎么了?

$ gcc --version gcc (Debian 4.4.5-8) 4.4.5 $ gcc --version 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 $ uname -a Linux深度站(挤压)2.6.32-5-686#1 SMP Fri May 10 08:33:48 UTC 2013 i686 GNU / Linux

You are trying to write to an uninitialized pointer out . 您正在尝试写入未初始化的指针out That's why you crash. 这就是为什么你崩溃。 It is badly undefined behaviour. 这是非常不确定的行为。 The magic is coincidental; 魔术是巧合; it does not make the behaviour any better defined. 它不会使行为得到更好的定义。

It is probably best to use vsnprintf() : 最好使用vsnprintf()

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

Or something similar. 或类似的东西。

You can improve this. 您可以改善这一点。 For example: 例如:

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

Make sure you free the allocated memory in the calling code. 确保在调用代码中释放分配的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM