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;
}
相关推荐
虾球xz3 分钟前
游戏引擎学习第272天:显式移动转换
c++·学习·游戏引擎
(ღ星辰ღ)9 分钟前
js应用opencv
开发语言·javascript·opencv
HY小海21 分钟前
【数据结构】双链表
c语言·开发语言·数据结构·学习
DK2215122 分钟前
计算机网络基础科普
c++·计算机网络
无畏烧风40 分钟前
[C++] 一个线程打印奇数一个线程打印偶数
c++
I AM_SUN42 分钟前
994. 腐烂的橘子
数据结构·c++·算法·leetcode·职场和发展
DARLING Zero two♡1 小时前
C++色彩博弈的史诗:红黑树
c++·红黑树
Go Dgg1 小时前
Go语言实现豆瓣电影Top250爬虫
开发语言·爬虫·golang
真的想上岸啊1 小时前
c语言第一个小游戏:贪吃蛇小游戏03
c语言·开发语言·算法
User_芊芊君子1 小时前
【Java继承】——面向对象编程的基石
java·开发语言