2

我对myname数组的生命周期感到困惑,它在if声明中还活着吗?我们在 c 和 c++ 中得到相同的答案吗?

int main (int argc, char* argv[])
{
    char* host;

    if (1 == argc)
    {
/*code below is copied from a book*/
        char myname[256];
        gethostname(myname, 255);
        host = myname;
/*code above is copied from a book*/
    }

    else
    {
        /*        */
    }
    printf("%s\n",host);

    return 0;
}

编辑:

代码片段来自本书Begining Linux Programming 4th edition,第15章:套接字,很抱歉作者犯了这样的错误。但我认为这本书很好,排除了这段代码。

4

3 回答 3

7

myname array's lifetime[;] is it still alive out of the if statement?

No

Do we get the same answer in C and C++?

Yes

It is ugly, bad code and has UB, use std::string for host

于 2013-01-11T02:40:27.500 回答
1

The myname array is destroyed at the end of the if. Printing host at this point might just work but is Undefined behavior, since you are using a pointer to memory that has been destroyed. Its functioning is implementation dependant (and other factors).

It is identical (destroyed => undefined) in both C and C++

于 2013-01-11T02:41:03.783 回答
0

Once you leave that if block there are no guarantees for myname[256]. There is nothing in the compiler that would keep track of the fact that host points to myname, in order to "keep it alive".

于 2013-01-11T02:41:28.890 回答