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;
}
相关推荐
工程师老罗几秒前
Python中__call__和__init__的区别
开发语言·pytorch·python
JSON_L2 分钟前
PHP项目打包为桌面应用
开发语言·php·桌面应用
2301_822366352 分钟前
C++中的协程编程
开发语言·c++·算法
m0_736919102 分钟前
C++中的事件驱动编程
开发语言·c++·算法
上海合宙LuatOS5 分钟前
LuatOS框架的使用(1)
java·开发语言·单片机·嵌入式硬件·物联网·ios·iphone
热爱编程的小刘8 分钟前
Lesson03---类与对象(中篇)
c++
小程同学>o<9 分钟前
嵌入式之C/C++(三)指针
c语言·c++·算法·嵌入式软件·嵌入式面试题库
lxl130711 分钟前
学习C++(4)构造函数+析构函数+拷贝构造函数
开发语言·c++·学习
阿kun要赚马内13 分钟前
Qt写群聊项目(二):客户端
开发语言·c++·qt
轩情吖16 分钟前
数据结构-并查集
开发语言·数据结构·c++·后端··并查集