gpt4 book ai didi

C++ - 函数返回,但不交回控制权

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:29:52 24 4
gpt4 key购买 nike

我正在使用 C++ 为 Linux 开发另一个套接字库,作为个人练习。这是我的代码:

#ifndef SOCKET_H
#define SOCKET_H

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;

/**
* Creates a struct to hold all the necessary information to create a socket.<br/>
* Typically, you should not need to call this yourself, as it is done when you call listen() or dial()
* @param host The hostname or IP address to connect to.
* @param service The service on that machine (e.g "http" or "80")
* @param sock The type of socket ("tcp" or "udp")
* @return A addrinfo struct with all the required information to create a connection.
*/
addrinfo setup(const char *host,const char *service,const char *sock) {
struct addrinfo hints;
struct addrinfo *serv;
cout << "2.call to setup()\n";
//cout << "3.setup() returns here.\n";
//return *serv;
int status=0;
/*struct addrinfo hints;
struct addrinfo *serv;*/

memset(&hints,0,sizeof hints);
hints.ai_family=AF_UNSPEC;
if (sock=="tcp") {
hints.ai_socktype=SOCK_STREAM;
} else if (sock=="udp") {
hints.ai_socktype=SOCK_DGRAM;
} else {
fprintf(stderr,"[!] xsockets: error: unknown socket type %s\n",sock);
exit(2);
}
hints.ai_flags=AI_PASSIVE;

if ((status=getaddrinfo(host,service,&hints,&serv))!=0) {
fprintf(stderr, "[!] xsockets: error: getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
cout << "3.setup() returns here.\n";
return *serv;
}

/**
* Listens on a portand returns a scoket file descriptor.
* @param service The service on this machine (e.g "http" or "80")
* @param sock The type of socket ("tcp" or "udp")
* @return A socket filde descriptor.
*/
int listen(const char *service,const char *sock) {
cout << "1.call to listen()\n";
struct addrinfo *serv;
*serv=setup(NULL,service,sock);
cout << "4.is this ever called?";
int sockfd=socket(serv->ai_family,serv->ai_socktype,serv->ai_protocol);
int status=bind(sockfd,serv->ai_addr,serv->ai_addrlen);
if (status!=0) {
fprintf(stderr,"[!] xsockets: error: bind error: %s\n",gai_strerror(status));
exit(3);
}
cout << "5.listen() returns here.";
return sockfd;
}
#endif

如果我运行它,它会到达#3“setup() 返回这里”但永远不会到达#4“这是否被调用过?”更不用说 #5 “listen() 在这里返回”

谁能告诉我哪里出了问题。

我在 Ubuntu Linux 上,以 root 权限运行它。它是用 g++ 命令编译的。

这是我得到的:

最佳答案

你有未定义的行为,因为你没有初始化指针 serv 但随后立即用 *serv 取消引用它。

尽管如此,在调试时,您应该确保通过将 std::flushstd::endl 插入 std::来刷新输出输出:

cout << "4.is this ever called?" << std::endl;

关于C++ - 函数返回,但不交回控制权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16125685/

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