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;
}
相关推荐
csdn_aspnet18 分钟前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
qq_2546744134 分钟前
Docker 中的 镜像(
开发语言
码云社区1 小时前
JAVA二手车交易二手车市场系统源码支持微信小程序+微信公众号+H5+APP
java·开发语言·微信小程序·二手交易·闲置回收
crescent_悦1 小时前
C++:The Largest Generation
java·开发语言·c++
paeamecium2 小时前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试
Lyyaoo.2 小时前
【JAVA基础面经】抽象类/方法与接口
java·开发语言
0xDevNull2 小时前
Java实现Redis延迟队列:从原理到高可用架构
java·开发语言·后端
糖炒栗子03262 小时前
Go 语言环境搭建与版本管理指南 (2026)
开发语言·后端·golang
于先生吖2 小时前
无人共享健身房 Java 后端源码 + 多端对接完整方案
java·开发语言
cpp_learners3 小时前
银河麒麟V10+飞腾FT-2000/4处理器+QT源码静态编译5.14.2指南
开发语言·qt