gpt4 book ai didi

c++ - 为什么我在 strcpy_s 之后得到 Debug assertion failed?

转载 作者:搜寻专家 更新时间:2023-10-31 00:48:53 25 4
gpt4 key购买 nike

我刚开始学习套接字,我得到了这段代码,我必须让端口查找逻辑工作。但问题是我不断收到此运行时错误,我不知道为什么?

// portlookup.cpp
// Given a service name, this program displays the corresponding port number.

#include <iostream>
#pragma comment(lib, "ws2_32.lib")
#include <winsock2.h>
using namespace std;

int main (int argc, char **argv)
{
char service[80]; // This string contains name of desired service
struct servent *pse; // pointer to service information entry
short port; // Port # (in Network Byte Order) of desired service

if (argc < 2)
{
cout << "Please specify a service." << endl;

}

strcpy_s(service, sizeof(service), argv[1]);

WORD wVersion = 0x0202;
WSADATA wsaData;
int iResult = WSAStartup(wVersion, &wsaData); // Returns zero if successful
if (iResult != 0) {
cout << "Insufficient resources to startup WINSOCK." << endl;
return 0;
}

port = htons( (u_short) atoi(service)); // 1st try to convert string to integer
if (port == 0) { // if that doesn't work, call service function
pse = getservbyname(service,NULL);
if (pse) {
port = pse->s_port;
}
else
{
cout << "Invalid service request." << endl;
return INVALID_SOCKET;
}
}

cout << "Service: " << service << endl;
cout << "Port: " << htons(port) << endl;

}

最佳答案

您的问题似乎是您没有传递命令行,您检查了 argc < 2,但是当它 < 2 时您仍然执行 strcpy_s。

在 Visual Studio 中,转到项目属性对话框,从那里转到调试页面并将服务名称添加到命令参数

并修复你的参数检查代码

if (argc < 2)
{
//cout << "Please specify a service." << endl;
cerr << "error: no service specified." << endl;
return EXIT_FAILURE; // return some non-zero value to indicate failure.
}

关于c++ - 为什么我在 strcpy_s 之后得到 Debug assertion failed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2214727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com