简体   繁体   中英

Why the error in the c++ code while use cout/cin?

I have this code:

#include<iostream>

int main() {
 char* name;
 std::cout<<"Ingresa tu nombre: \t";
 std::cin>>name;
 std::cout<<"Tu nombre es: \t"<<name;
 return 0;
}

When the variable name is of type int , it works fine, but when the variable is of type char , to store the whole name, when entering it the program says that it has stopped working, and does not even manage to show the name, in the last cout .

在此处输入图片说明

You're reading input into an uninitialized character buffer pointer, basically dumping input into some random chunk of memory, so this is undefined behaviour and it will crash.

You need to initialize that buffer prior to use, or, the C++ solution here is to use a string:

std::string name;

That handles memory management for you automatically and doesn't suffer from the buffer overflow problems intrinsic to C.

char* name; is a pointer. It needs to point to some memory. Currently it is uninitialized so it could point anywhere or to anything. This means when you do this; std::cin>>name; it will write randomly into your programs space as if it were writing into a buffer. This is undefined behaviour and can result in anything, including working correctly or crashing as it does in your case. In c++, you can use a std::string to read into:

std::string name;
std::cin>>name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM