简体   繁体   中英

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. This is what I get when delete 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.

#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. It's contents is indeterminate and will be seemingly random. Using it as a destination for a strcpy call will lead to undefined behavior .

If you want to use C-style strings, you need to allocate memory for name , for example by using an array:

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? For example the std::string class that are very good at handling strings:

#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. When you strcpy to it, you trample five bytes at that location, replacing them with 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.


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);

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