简体   繁体   English

在cout <<“ hello” << endl中删除endl之后,我的C ++程序停止工作

[英]after delete endl in cout << “hello” << endl, my C++ program stopped working

This is my code. 这是我的代码。 This code can run well. 此代码可以很好地运行。 But when I delete "endl" in "cout << "Hello world!" << endl;", It can't run. 但是在删除“ cout <<” Hello world!“ << endl;”中的“ endl”时,它无法运行。 This is what I get when delete endl 这是删除endl时得到的

#include <iostream>
#include <cstring>

using namespace std;
int main()
{
    char * name;
    char * n = "aaaa";
    strcpy(name, n);
    cout << name;
    cout << "Hello world!" << endl;
    return 0;
}

The following is the code that deleted endl. 以下是删除endl的代码。

#include <iostream>
#include <cstring>

using namespace std;
int main()
{
    char * name;
    char * n = "aaaa";
    strcpy(name, n);
    cout << name;
    cout << "Hello world!";
    return 0;
}

Lets take a look at these lines: 让我们看一下这些行:

char * name;
char * n = "aaaa";
strcpy(name, n);

The variable name is not initialized. 变量name未初始化。 It's contents is indeterminate and will be seemingly random. 它的内容是不确定的 ,似乎是随机的。 Using it as a destination for a strcpy call will lead to undefined behavior . 将其用作strcpy调用的目标将导致未定义的行为

If you want to use C-style strings, you need to allocate memory for name , for example by using an array: 如果要使用C样式的字符串,则需要为name分配内存,例如,使用数组:

char name[128];

But if you are actually programming in C++, why don't you use the awesome classes that comes with the standard library? 但是,如果您实际上是用C ++进行编程,那么为什么不使用标准库随附的超棒类呢? For example the std::string class that are very good at handling strings: 例如, std::string类非常擅长处理字符串:

#include <string>
#include <iostream>

int main()
{
    std::string name;
    std::string n = "aaaa";

    name = n;

    std::cout << name << '\n';
    std::cout << "Hello world" << std::endl;
}

name is an uninitialized pointer : it points at some random memory location. name是一个未初始化的指针:它指向某个随机存储器位置。 When you strcpy to it, you trample five bytes at that location, replacing them with aaaa\\0 . 当你strcpy它,你践踏五个字节在该位置,与替换它们aaaa\\0

Formally, this is undefined behaviour. 形式上,这是不确定的行为。 In practice, you have witnessed two different symptoms : no apparent effect, and a crash. 在实践中,您目睹了两种不同的症状:没有明显的效果和崩溃。

Point name at a sufficiently large buffer that you actually own, and all will be fine. name指向您实际拥有的足够大的缓冲区,一切都会好的。


char * name;
This line 'name' is not initialised and holds garbage. 此行“名称”未初始化,并且保留垃圾。
Instead do something like: 而是执行以下操作:

 using namespace std;
 int main(){

   char name[10];
   char  *n = "aaaa";
   strcpy(name, n);
   cout << name;
   cout << "Hello world!";

   return 0;
}

You're copying into a garbage address. 您正在复制到垃圾地址。

char * name; //<<<garbage address
char * n = "aaaa";
strcpy(name, n);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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