尝试检索指针的内容时程序崩溃

Program crashes when trying to retrieve contents of pointer

我正在使用 winsock2 在 C++ 中制作一个套接字程序,我正在尝试使用 WSAAccept 有条件地接受连接。我从 MSDN 中为 WSAAccept 中的 lpfnCondition 参数复制了示例 ConditionalFunction,如下所示。

SOCKET WSAAccept(
  _In_    SOCKET          s,
  _Out_   struct sockaddr *addr,
  _Inout_ LPINT           addrlen,
  _In_    LPCONDITIONPROC lpfnCondition, //<---------
  _In_    DWORD_PTR       dwCallbackData
);

然而,当像这样 WSABUF buffer = *lpCallerData 尝试访问 ConditionalFunctionlpCallerId 的内容时,我的程序崩溃了。我知道这是问题的根源,因为当我评论那一行时,我的程序不会崩溃。我不认为我所有的代码都是必要的。任何帮助都会很可爱。

编辑:

CALLBACK ConditionalAccept(LPWSABUF lpCallerId,LPWSABUF lpCallerData,LPQOS lpSQOS,
                           LPQOS lpGQOS,LPWSABUF lpCalleeId,LPWSABUF lpCalleeData,
                           GROUP *g,DWORD_PTR dwCallbackData)
{
    WSABUF buffer = *lpCallerData;

    if (lpSQOS != NULL) {
        RtlZeroMemory(lpSQOS, sizeof(QOS));
        return CF_ACCEPT;
    } else
        return CF_REJECT;
}

...

WSAAccept(slisten, (SOCKADDR*)&acceptSock, &Size, &ConditionalAccept, NULL);

正如 Luke 所说,在取消引用之前,您没有检查 lpCallerData 是否为 NULL。这就是您的代码崩溃的原因。

int CALLBACK ConditionalAccept(LPWSABUF lpCallerId,LPWSABUF lpCallerData,LPQOS lpSQOS,
                           LPQOS lpGQOS,LPWSABUF lpCalleeId,LPWSABUF lpCalleeData,
                           GROUP *g,DWORD_PTR dwCallbackData)
{
    WSABUF buffer = {0};

    if (lpCallerData != NULL) { // <-- add this check!
        buffer = *lpCallerData;
    }

    if (lpSQOS != NULL) {
        RtlZeroMemory(lpSQOS, sizeof(QOS));
        return CF_ACCEPT;
    } else
        return CF_REJECT;
}

但是,lpCallerData 在 TCP/IP 中没有意义,并且 总是 为 NULL。 TCP/IP 不支持在连接建立期间交换 caller/callee 数据。这在 WSAConnect() 文档中有明确说明:

The lpCallerData parameter contains a pointer to any user data that is to be sent along with the connection request (called connect data). This is additional data, not in the normal network data stream, that is sent with network requests to establish a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others.

Note Connect data is not supported by the TCP/IP protocol in Windows. Connect data is supported only on ATM (RAWWAN) over a raw socket.