Cout在声明一个std::string变量后不给出任何输出
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();
- 第一个对象将在堆中创建,并在函数运行完毕后自动删除
- 第二个对象将在堆栈中创建,并且必须使用delete/delete[]运算符手动执行内存释放
那么,在处理指针时,我还应该记住什么呢?我想我需要读一本关于计算机体系结构的好书,因为关于内存和微处理器的知识会带来利润:(
相关文章:
- 如果我注释掉换行符,为什么'string'会成为一个不合格的变量
- GDB 8.1 无法在单线程简单程序中跟踪 std::string 变量的值
- 为什么当我使用 std::string::operator[] 时自动变量不会成为引用?
- 使用词法强制转换在'string to double'中设置双精度变量的精度
- 检查 std::any 变量是否包含 std::string 时出现问题
- 变量参数列表 后面的'const std::string&'弄乱了堆栈
- 变量具有不完整的类型std :: String;string.h有很多错误
- 如何有效地将底层数据从 std::string 移动到其他类型的变量?
- 如何在系统( "say string variable" )中使用字符串变量?
- 初始化 std::string& 的私有类变量
- 在 std::string 变量中使用提升库存储文件名
- C SEG故障在STD :: String Destructor上,仅当传递变量时
- 围绕变量[String]的堆叠为损坏的C
- c++如何打印另一种类型的变量的String属性的值
- 如何获取字符串形式的int变量的长度内置函数,例如string.length()
- C++ 在列表变量名称中查找字符串字符串<string>
- 从包含表示约 64 GB 值的十进制数的 String 变量中获取值
- 将 wstring、string 和对枚举变量的引用从 C# 传递到 C++(非托管 DLL)
- 您是否需要析构函数来销毁全局 int、float 或 std::string 变量
- 定义静态常量 std::string 类变量