簡體   English   中英

為什么這個C ++代碼在ideone.com上獲得SIGILL?

[英]Why does this C++ code get SIGILL on ideone.com?

為什么會這樣? 該代碼在Linux上運行GCC 4.7,在Windows上運行MSVC ++ 2010時不會生成警告。 然而,在ideone.com上,它與SIGILL 崩潰了。 這里涉及到未定義的行為嗎?

#include <iostream>
#include <cstdarg>

using namespace std;

enum types
{
    INT,
    DOUBLE,
    CHAR,
    STRING
};

struct mt
{
    types type;

    union
    {
        int         i;
        double      d;
        char        c;
        const char *s;
    } val;

    mt(int i)
        : type(INT)
    {
        val.i = i;
    }

    mt(double d)
        : type(DOUBLE)
    {
        val.d = d;
    }

    mt(char c)
        : type(CHAR)
    {
        val.c = c;
    }

    mt(const char *s)
        : type(STRING)
    {
        val.s = s;
    }
};

void print(int n, ...)
{
    va_list ap;

    va_start(ap, n);

    for (int i = 0; i < n; i++)
    {
        mt x(va_arg(ap, mt));

        switch (x.type)
        {
        case INT:
            cout << x.val.i << endl;
            break;
        case DOUBLE:
            cout << x.val.d << endl;
            break;
        case CHAR:
            cout << x.val.c << endl;
            break;
        case STRING:
            cout << x.val.s << endl;
            break;
        }
    }

    va_end(ap);
}

int main()
{
    print(4, mt(2), mt(4.2), mt('a'), mt("Hello"));
}

我在GCC 4.4.6中遇到錯誤:

test.cpp: In function ‘void print(int, ...)’:
test.cpp:59: warning: cannot receive objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
test.cpp: In function ‘int main()’:
test.cpp:83: warning: cannot pass objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
test.cpp:83: warning: cannot pass objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
test.cpp:83: warning: cannot pass objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
test.cpp:83: warning: cannot pass objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
$ g++ --version
g++ (GCC) 4.4.6 20110731 (Red Hat 4.4.6-3)

你不能通過varargs函數參數傳遞struct ,而是傳遞指針:

void print(int n, ...)
{
    va_list ap;

    va_start(ap, n);

    for (int i = 0; i < n; i++)
    {
        mt *x(va_arg(ap, mt *));

        switch (x->type)
        {
        case INT:
            cout << x->val.i << endl;
            break;
        case DOUBLE:
            cout << x->val.d << endl;
            break;
        case CHAR:
            cout << x->val.c << endl;
            break;
        case STRING:
            cout << x->val.s << endl;
            break;
        }
    }

    va_end(ap);
}

int main()
{
    mt mt1(2);
    mt mt2(4.2);
    mt mt3('a');
    mt mt4("Hello");
    print(4, &mt1, &mt2, &mt3, &mt4);
}

哪個在我的系統上工作正常:

$ ./a.out
2
4.2
a
Hello

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM