std::cout打印空的char指针会出现未定义行为

使用std::cout打印char类型的指针,如果这个指针为空的话,那么会导致后边使用std::cout进行的打印都不显示。

如下代码,分别打印非空的char指针,空的char指针,空的int指针,运行结果如下:

(1)打印非空的char指针,执行正常。

(2)打印空的char指针,会导致后边的std::cout打印都打印不出来。

(3)打印空的int指针,没有影响,将空指针当成0打印了出来。

root@wangyanlong-virtual-machine:/home/wangyanlong/cpp# ./a.out 1

1 before print

p=hello

1 after print

root@wangyanlong-virtual-machine:/home/wangyanlong/cpp# ./a.out 2

2 before print

p=root@wangyanlong-virtual-machine:/home/wangyanlong/cpp# ./a.out 3

3 before print

p=0

3 after print

root@wangyanlong-virtual-machine:/home/wangyanlong/cpp#

cpp 复制代码
#include <iostream>
#include <string>
#include <unistd.h>

int main(int32_t argc, char** argv) {
  if(argc != 2) {
    std::cout << "usage:./a.out 1/2/3" << std::endl;
    return 0;
  }

  if (std::string(argv[1]) == "1") {
    char *p = "hello";
    std::cout << "1 before print" << std::endl;
    std::cout << "p=" << p << std::endl;
    std::cout << "1 after print" << std::endl;
  } else if (std::string(argv[1]) == "2") {
    char *p = nullptr;
    std::cout << "2 before print" << std::endl;
    std::cout << "p=" << p << std::endl;
    std::cout << "2 after print" << std::endl;
  } else if (std::string(argv[1]) == "3") {
    int *p = nullptr;
    std::cout << "3 before print" << std::endl;
    std::cout << "p=" << p <<std::endl;
    std::cout << "3 after print" << std::endl;
  }

  return 0;
}
相关推荐
YxVoyager21 分钟前
【C++标准库】<ios>详解基于流的 I/O
c语言·c++
code bean2 小时前
【C#】获取不重复的编码(递增,非GUID)
开发语言·c#
阿里嘎多哈基米2 小时前
二、JVM 入门——(三)栈
java·开发语言·jvm·线程·
雷达学弱狗3 小时前
anaconda本身有一个python环境(base),想用别的环境就是用anaconda命令行往anaconda里创建虚拟环境
开发语言·python
燃尽余火3 小时前
Knife4j 文档展示异常的小坑
java·开发语言·spring
tan77º3 小时前
【项目】分布式Json-RPC框架 - 抽象层与具象层实现
linux·服务器·c++·分布式·tcp/ip·rpc·json
zzx_blog3 小时前
c++函数工厂实现两种方式:lambda和function
c++
mit6.8243 小时前
[pilot智驾系统] 自动驾驶守护进程(selfdrived)
linux·c++·自动驾驶
jokr_3 小时前
C++ STL 顶层设计与安全:迭代器、失效与线程安全
java·c++·安全
爬虫程序猿4 小时前
利用 Java 爬虫按关键字搜索 1688 商品详情 API 返回值说明实战指南
java·开发语言·爬虫