简体   繁体   中英

Strange file output C++

I wanted to print the numbers and put a space between them but just after the compile I noticed I left that + operator in there (C# practice). When I ran this program, it stopped working immediately but there is a very strange output in the text file. Why is the text file like that?

#include <iostream>
#include <fstream>
using namespace std;

    int main()
    {
        int i=0;
        ofstream f("out.txt");
        while(i != -1)
        {
            f << " " + i++;
        }
        return 0;
    }

Some lines from the 551Kb file:

deleted virtual method called
eleted virtual method called
leted virtual method called
eted virtual method called
ted virtual method called
ed virtual method called
d virtual method called
 virtual method called
virtual method called
irtual method called
rtual method called
tual method called
ual method called
al method called
l method called
 method called
method called
ethod called
thod called
hod called
od called
d called
 called
called
alled
lled
led
ed
d

When you add an integer to a string literal, it performs pointer arithmetic. So " " + i++ gets the address of the string literal, adds i to it, and increments i . Then it passes the result of the addition to << , so whatever C-style string is at that address gets printed to the file.

Since you're accessing outside the bounds of the string literal's memory, this results in undefined behavior. So it's writing garbage to the file. It looks like the memory after your string literal contains an internal error message from the runtime library, and you're printing that string. Since i gets incremented each time, each iteration starts one character later in the message.

You also have a practically infinite loop because incrementing i won't result in -1 until it overflows and wraps around.

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