引数として渡された IP アドレスのホスト名を返す簡単なプログラムを作成しました。このプログラムは、getaddrinfo() と getnameinfo() の 2 つの関数を使用します。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;
}