我编写了一个简单的程序,返回作为参数传递的 IP 地址的主机名。
该程序使用两个函数:getaddrinfo() 和 getnameinfo()。
我正在使用 Linux Mint、Netbeans IDE 和 G++ 编译器。输出没问题,没有错误,但是当我声明一个
std::string str;
然后 cout 没有输出,屏幕上没有打印任何内容。但是,当我注释掉 std::string 声明或删除它时,该语句
std::cout << "hostname: " << hostname << std::endl;
成功打印返回的主机名。
造成这种奇怪错误的原因可能是什么?
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <iostream>
#include <string>
int main()
{
struct addrinfo* result;
struct addrinfo* res;
int error;
const char* host;
// When I comment out this line, cout prints the hostnames succesfully.
std::string str;
error = getaddrinfo("127.0.0.1", NULL, NULL, &result);
res = result;
while (res != NULL)
{
char* hostname;
error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, 1025, NULL, 0, 0);
std::cout << "hostname: " << hostname << std::endl;
res = res->ai_next;
}
freeaddrinfo(result);
// When I declare an std::string str variable, this cout doesn't either print anything
std::cout << "TEST" << std::endl;
return 0;
}
The arguments host and serv are pointers to caller-
allocated buffers (of size hostlen and servlen respectively) into which
getnameinfo() places null-terminated strings containing the host and
service names respectively.
http://man7.org/linux/man-pages/man3/getnameinfo.3.html http://man7.org/linux/man-pages/man3/getnameinfo.3.html
您的指针必须实际分配。注释掉该行会改变任何内容,这一事实可能是巧合或优化的奇怪副作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)