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;
}
相关推荐
缺点内向1 小时前
如何在 C# 中将 Excel 工作表拆分为多个窗格
开发语言·c#·.net·excel
少废话h2 小时前
解决Flink中ApacheCommonsCLI版本冲突
开发语言·python·pycharm
天命码喽c2 小时前
GraphRAG-2.7.0整合Milvus-2.5.1
开发语言·python·milvus·graphrag
后端小张2 小时前
【JAVA进阶】Spring Boot 核心知识点之自动配置:原理与实战
java·开发语言·spring boot·后端·spring·spring cloud·自动配置
Mr_Xuhhh7 小时前
YAML相关
开发语言·python
阿巴~阿巴~7 小时前
JsonCpp:C++ JSON处理利器
linux·网络·c++·json·tcp·序列化和反序列化
咖啡の猫7 小时前
Python中的变量与数据类型
开发语言·python
前端达人7 小时前
你的App消息推送为什么石沉大海?看Service Worker源码我终于懂了
java·开发语言
汤姆yu7 小时前
基于springboot的电子政务服务管理系统
开发语言·python
全栈师7 小时前
C#中控制权限的逻辑写法
开发语言·c#