我编写了一个简单的程序,返回作为参数传递的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;
}发布于 2013-04-06 05:26:43
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
您的指针必须实际分配。注释掉这一行可能是巧合,也可能是优化的一个奇怪的副作用。
发布于 2013-04-06 05:57:28
谢谢,它现在可以工作了:)。我想知道什么时候使用不同的方式来分配内存。据我所知,创建对象的主要区别如下:
// Creating objects:
Test t1;
Test* t2 = new Test();手动完成内存释放
那么,在处理指针时,我还应该记住什么呢?我想我需要读一本关于计算机体系结构的好书,因为关于内存和微处理器的知识将带来好处:)
https://stackoverflow.com/questions/15843820
复制相似问题