简体   繁体   中英

C++ Print Weird Behavior (Potential Memory Leak?)

I'm running some C++ code and have been noticing some weird behavior. For instance, my std::cout prints are only printing out a part of the string that I tell it to print.

Here is a small section of my code (this code gets called repeatedly):

std::ofstream file;
file.open("cout_img.txt", std::ofstream::out | std::ofstream::app);
std::streambuf* sbuf = std::cout.rdbuf();
std::cout.rdbuf(file.rdbuf());
std::cout << "Reached Display Function NOW";
std::string frame_file_name = std::string("demo") + std::to_string(saveImgNum) + std::string(".bmp");
std::cout << frame_file_name + '\n';

For instance, in this section I'm only printing out "splay Function NOW" each time instead of the full string "Reached Display Function NOW". I'm also not even printing out the frame_file_name variable.

Could this mean I'm experiencing a memory leak somewhere? If so, does the section of code I posted look suspicious at all? Is it because I have to deallocate variables such as the std::string variable?

What else can I look for? I'm using CPython API (Python embedded in C++) if that makes a difference.

Thanks so much!

If you just want to write to a file (as a console replacement / log), then there is no reason to redirect your output through std::cout .

I took your snippet and cut it down. This:

int main()
{
    std::ofstream file;
    file.open("cout_img.txt", std::ofstream::out | std::ofstream::app);

    file << "Reached Display Function NOW\n";
    std::string frame_file_name = std::string("demo") + std::to_string(17 /*saveImgNum*/) + std::string(".bmp");
    file << frame_file_name + '\n';

    return 0;
}

Produces a file cout_img.txt containing:

Reached Display Function NOW
demo17.bmp

EDIT: Additionally, you can also enable the console in your windows app. A quick search lead to this answer . Add the following code to your WinMain , and the console will work:

    AllocConsole();
    #pragma warning( disable : 4996 )
    freopen("conin$", "r", stdin);
    freopen("conout$", "w", stdout);
    freopen("conout$", "w", stderr);
    printf("Debugging Window:\n");
    std::cout << "Testing the console 1 2 3" << std::endl;

If you do a more thorough search, you can probably even find a method that doesn't use a deprecated method ( freopen ). But as shown there it did add a functioning console to the windows app that I just created to test with.

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