首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cout在声明std::string变量后没有输出

Cout在声明std::string变量后没有输出
EN

Stack Overflow用户
提问于 2013-04-06 05:22:52
回答 2查看 509关注 0票数 1

我编写了一个简单的程序,返回作为参数传递的IP地址的主机名。该程序使用两个函数: getaddrinfo()和getnameinfo()。我使用的是Linux Mint、Netbeans IDE和G++编译器。输出是正确的,没有错误,但是当我声明一个

代码语言:javascript
复制
std::string str;

然后cout不会输出,屏幕上也不会打印任何内容。但是,当我注释掉std::string声明或删除它时,语句

代码语言:javascript
复制
std::cout << "hostname: " << hostname << std::endl;

成功打印返回的主机名。

出现这种奇怪错误的原因可能是什么?

代码语言:javascript
复制
#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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-06 05:26:43

代码语言:javascript
复制
   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

您的指针必须实际分配。注释掉这一行可能是巧合,也可能是优化的一个奇怪的副作用。

票数 3
EN

Stack Overflow用户

发布于 2013-04-06 05:57:28

谢谢,它现在可以工作了:)。我想知道什么时候使用不同的方式来分配内存。据我所知,创建对象的主要区别如下:

代码语言:javascript
复制
// Creating objects:
Test t1;
Test* t2 = new Test();

  1. 第一个对象将在堆中创建,并在函数运行结束时自动删除。
  2. 第二个对象将在堆栈中创建,必须使用delete/delete[]运算符?

手动完成内存释放

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15843820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档