Cout在声明一个std::string变量后不给出任何输出

Cout gives no output after declaring an std::string variable

本文关键字:变量 string 输出 任何 std 声明 一个 Cout      更新时间:2023-10-16

我编写了一个简单的程序,返回作为参数传递的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();
  1. 第一个对象将在堆中创建,并在函数运行完毕后自动删除
  2. 第二个对象将在堆栈中创建,并且必须使用delete/delete[]运算符手动执行内存释放

那么,在处理指针时,我还应该记住什么呢?我想我需要读一本关于计算机体系结构的好书,因为关于内存和微处理器的知识会带来利润:(