2011-11-18 26 views
1
//this is server side code snippet used for chat application 

int* sockPtr; 
int result; 
result=listen(sClient,10); //sClient is SOCKET that is bind to specific port for listining incoming connection 
sockPtr = (int*)malloc(sizeof(int));   
*sockPtr= accept(sClient,(SOCKADDR*)&client_info,&addrlen); //here is the problem on sockPtr [which is integer type pointer] 

但是當客戶端試圖連接有一個例外說異常而調用accept()

Unhandled exception at 0x0041ce6b in server.exe: 0xC0000005: 
Access violation reading location 0x0000000. 

我該怎麼辦?

+0

我建議你檢查函數中的所有參數和返回代碼,看看它們是否都可以。 –

回答

0

Access violation reading location 0x0000000意味着你有一個空指針訪問。 malloc可能因爲內存不足而返回空指針,或者您的問題位於其他位置。我對套接字編程瞭解不多,但*sockPtr= accept(...)看起來很懷疑。

2

當調用accept()時,第二個參數是您提供用於存儲地址信息的緩衝區,這取決於您正在偵聽的套接字的地址族。

因此,在第二個參數中指定的緩衝區必須調用accept()之前申報和分配,第三個參數應包含緩衝區分配的大小。該函數將填充緩衝區並返回由請求的信息填充的緩衝區的實際長度。

類似:

struct sockaddr_in client_info; 
int    client_info_length; 
[...] 

client_info_length = sizeof(client_info); 
*sockPtr= accept(sClient,(SOCKADDR*)&client_info,&client_info_length); 

struct sockaddr_in結構存儲的地址的 「因特網」 地址族(TCP/IP)。如果您使用的是其他協議(我懷疑...),請使用適當的結構。

+0

我的意思是'struct sockaddr_in',因爲沒有typedef,你絕對需要這個'struct'關鍵字。 –