函数不会返回到它应该的位置

时间:2014-04-07 12:10:53

标签: c crash return

好的,所以我有一个尝试连接服务器的客户端。我打电话给下面的功能。功能完成之后'工作并即将返回客户端程序崩溃。我使用调试器,我注意到一个非常不寻常的事情。 return语句控制跳转到未知函数后(据我所知)。 IDE(Code :: Blocks)在客户端崩溃之前打印出来:

  

在C:... \ client.c:55

     

在?? ()()

     

发现失败"堆栈级别"失败匹配reg_output

     

编程接收信号SIGSEGV,分段故障。

以下是代码:

SOCKET InitializeClient( void )
{
    SOCKET ClientsockDesc;
    char ServerHostName [256] = {0};
    unsigned short int ServerPortNumber;
    struct sockaddr_in ServerAddress;
    struct hostent *ptrServerHostEntry = NULL;
    char Temp [10] = {0};
    const char yes = '1';
    char* Packet;

    while( 0 == strcmp(ServerHostName, "") )
    {
        printf("Input the host name: ");
        fgets(ServerHostName, sizeof(ServerHostName), stdin);
    }
    ServerHostName[strlen(ServerHostName) - 1] = '\0';

    while( 0 == strcmp(Temp, "") )
    {
        printf("Input the server port number: ");
        fgets(Temp, sizeof(Temp), stdin);
    }
    Temp[strlen(Temp) - 1] = '\0';
    ServerPortNumber = (unsigned short int)atoi(Temp);

    if( NULL ==(ptrServerHostEntry = gethostbyname(ServerHostName)) )
        return INVALID_SOCKET;

    ServerAddress.sin_family    = AF_INET;
    ServerAddress.sin_port      = htons( ServerPortNumber );
    ServerAddress.sin_addr      = *(struct in_addr *)ptrServerHostEntry->h_addr;
    memset(&(ServerAddress.sin_zero), 0, 8);
    if( INVALID_SOCKET ==(ClientsockDesc = socket(AF_INET, SOCK_STREAM, 0)) )
        return INVALID_SOCKET;
    if( SOCKET_ERROR == setsockopt(ClientsockDesc,
        SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) )
        return INVALID_SOCKET;
    if( SOCKET_ERROR == connect(ClientsockDesc, (struct sockaddr *)&ServerAddress, sizeof(struct sockaddr)) )
    {
        closesocket(ClientsockDesc);
        return INVALID_SOCKET;
    }
    printf("Successfully connected to host \'%s\' -(%s).\n",
        ServerHostName, inet_ntoa(*(struct in_addr *)ptrServerHostEntry->h_addr) );
    if( SOCKET_ERROR == ReceivePacket(&ClientsockDesc, Packet) )
    {
        closesocket(ClientsockDesc);
        return INVALID_SOCKET;
    }
    printf("%s", Packet);
    return ClientsockDesc;
}

任何帮助将不胜感激。我很乐意提供任何其他信息。

1 个答案:

答案 0 :(得分:1)

您正在将未经过uninitilized的变量传递给ReceivePacket:

char* Packet;

<skipped lines>

if( SOCKET_ERROR == ReceivePacket(&ClientsockDesc, Packet) )
{

C按值传递,这意味着在通话结束后,Packet仍然未初始化。