[英]Cout gives no output after declaring an std::string variable
我寫了一個簡單的程序,返回作為參數傳遞的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
你的指針必須實際分配。 評論該行改變任何事情的事實可能是優化的巧合或奇怪的副作用。
謝謝,它現在有效:)。 我想知道何時使用不同的方式來分配內存。 據我所知,以下列方式創建對象之間的主要區別:
// Creating objects:
Test t1;
Test* t2 = new Test();
那么在處理指針時我還應該記住什么呢? 我想我需要閱讀一本關於計算機體系結構的好書,因為有關內存和微處理器的知識會帶來利潤:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.