调用 connect() 时程序崩溃
Program Crashes when making call to connect()
我扔了一些打印语句,发现我的程序在调用connect()
时崩溃了。 我做了一些谷歌搜索并查看了代码,不确定发生了什么,我在连接呼叫之前打电话给GetLastError()
,没有任何问题,程序中没有任何问题,然后整个事情立即崩溃。很明显,它甚至没有尝试连接到服务器,并且由于崩溃而无法打印出任何内容。
所以,我不知道这里发生了什么,我常用的方法都不起作用,因为程序在没有输出任何输出的情况下崩溃,并且没有任何问题。
WSAData wsaData;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
#ifdef debug
printf("WSAStartup failed: %dn", 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: %dn%dn", 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()
您必须将result
分配给ptr
。否则,您将取消引用 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: %dn%dn", 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: %ldn", WSAGetLastError());
WSACleanup();
return 1;
}
请看这个例子:
完整的 Winsock 客户端代码
相关文章:
- 程序崩溃并显示"std::out_of_range"错误
- 试图创建流或fopen时程序崩溃
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 如何找出应用程序崩溃的原因 - Win 10 LTSB
- 操纵安卓相机的深度图导致应用程序崩溃
- 为什么当我尝试搜索双链表中第一个数据条目之外的数据时,程序崩溃了?
- DLL Made with CMake 使程序崩溃
- 程序崩溃使用boost::asio
- 调用 free() 有时会导致程序崩溃
- 邮件加密程序崩溃
- 调用 java 的回调() 时应用程序崩溃.由于 detatchThread 而获得运行时错误
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- For 循环在尝试读取数组 c++ 时程序崩溃
- 即使有 0 个错误,Getter 似乎也会使程序崩溃
- Windows桌面程序保存您的计算机会话 - 基于程序崩溃时的恢复会话
- 无法访问的代码如何导致我的程序崩溃?
- 矢量迭代器在尝试调用函数时使我的程序崩溃
- QCompleter set模型使应用程序崩溃
- 使用唯一指针调用函数会使我的程序崩溃
- 删除SDL_PollEvent时程序崩溃