当前位置: 动力学知识库 > 问答 > 编程问答 >

c - 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

$ uname -a

Linux deep-station (squeeze) 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. 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():

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: