2016-01-18 25 views
-1

我投擲了一些打印語句,發現我的程序在撥打connect()時崩潰。我做了一些谷歌搜索,並查看了代碼,並且不確定發生了什麼,我在連接調用之前調用了GetLastError(),沒有發生錯誤,程序中沒有任何錯誤,然後整個事件立即崩潰。 它很明顯不甚至試圖連接到服務器,並且之後沒有任何內容會被打印出來,因爲它已經崩潰。
所以,我不知道這裏發生了什麼,也沒有我的平常方法可以工作,因爲程序在沒有輸出任何輸出的情況下崩潰,並且沒有任何事情會發生。程序在撥打連接電話時崩潰()

WSAData wsaData; 

int iResult; 

// Initialize Winsock 
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); 
if (iResult != 0) { 

#ifdef debug  
    printf("WSAStartup failed: %d\n", iResult); 
#endif 

    return 1; 
} 

struct addrinfo *result = NULL, 
    *ptr = NULL, 
    hints; 

ZeroMemory(&hints, sizeof(hints)); 
hints.ai_family = AF_UNSPEC; 
hints.ai_socktype = SOCK_STREAM; 
hints.ai_protocol = IPPROTO_TCP; 

#define DEFAULT_PORT "80" 

std::string www = "tildetictac.x10host.com"; 
// Resolve the server address and port 
iResult = getaddrinfo(www.c_str(), DEFAULT_PORT, &hints, &result); 
if (iResult != 0) { 
#ifdef debug 
    printf("getaddrinfo failed: %d\n%d\n", iResult, GetLastError()); 
#endif 
    WSACleanup(); 
    return 1; 
} 
else { 
#ifdef debug 
    std::cout << "success \n"; 
#endif 
} 

SOCKET connectSocket = INVALID_SOCKET; 

printf("error: %d", GetLastError()); 

// Connect to server. 
iResult = connect(connectSocket, ptr->ai_addr, (int)ptr->ai_addrlen); 
std::cout << "2"; 
// this doesn't get printed before the crash, so its for sure connect() 
+2

的代碼可以在'connect'呼叫崩潰是,如果'ptr'是無效的唯一途徑。而且我沒有看到它在任何地方都被分配了非空值。 –

+3

此外,'connectSocket'設置爲'INVALID_SOCKET',然後嘗試連接它。看起來像你只寫了一半你的程序。 –

+0

傳遞給函數調用的參數的確切值是什麼? –

回答

0

你必須分配給resultptr。否則,你正在取消引用NULL指針,這將導致崩潰。

std::string www = "tildetictac.x10host.com"; 
    // Resolve the server address and port 
    iResult = getaddrinfo(www.c_str(), DEFAULT_PORT, &hints, &result); 
    if (iResult != 0) { 
    #ifdef debug 
     printf("getaddrinfo failed: %d\n%d\n", iResult, GetLastError()); 
    #endif 
     WSACleanup(); 
     return 1; 
    } 
    else { 
    #ifdef debug 
     std::cout << "success \n"; 
    #endif 
    } 

    ptr = result; //ADDED 

    // Create a SOCKET for connecting to server 
    connectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
      ptr->ai_protocol); 
    if (connectSocket == INVALID_SOCKET) { 
     printf("socket failed with error: %ld\n", WSAGetLastError()); 
     WSACleanup(); 
     return 1; 
    } 

請看看這個例子:

Complete Winsock Client Code