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;
}
相关推荐
Brookty41 分钟前
Java线程安全与中断机制详解
java·开发语言·后端·学习·java-ee
從南走到北2 小时前
JAVA东郊到家按摩服务同款同城家政服务按摩私教茶艺师服务系统小程序+公众号+APP+H5
android·java·开发语言·微信小程序·小程序
遇见尚硅谷2 小时前
C语言:20250728学习(指针)
c语言·开发语言·数据结构·c++·笔记·学习·算法
☆璇2 小时前
【C++】C/C++内存管理
c语言·开发语言·c++
愿你天黑有灯下雨有伞3 小时前
枚举策略模式实战:优雅消除支付场景的if-else
java·开发语言·策略模式
网络安全打工人3 小时前
CentOS7 安装 rust 1.82.0
开发语言·后端·rust
楚轩努力变强3 小时前
前端工程化常见问题总结
开发语言·前端·javascript·vue.js·visual studio code
梦想的初衷~3 小时前
MATLAB近红外光谱分析技术及实践技术应用
开发语言·支持向量机·matlab
Fly-ping3 小时前
【前端】JavaScript文件压缩指南
开发语言·前端·javascript
铭哥的编程日记3 小时前
《C++ list 完全指南:从基础到高效使用》
开发语言·c++·list