Home > Software design >  CopyFile() function causes exception while debugging but not while running from terminal
CopyFile() function causes exception while debugging but not while running from terminal

Time:10-13

I have a Visual Studio 2019 project, containing only one .cpp file, named as copyFile.cpp

#undef UNICODE

#include <iostream>
#include <Windows.h>

int main()
{
    std::cout << "Hello World!\n";

    DWORD ret = CopyFile("xyz.txt", "xyzCopy.txt", FALSE);
    printf("\n\t ret: %d, getlasterror(): %d", ret, GetLastError());
    
    return 0;
}

There is a problem while debugging the code, stepping over this line:

DWORD ret = CopyFile("xyz.txt", "xyzCopy.txt", FALSE);

causes an exception to be thrown.

Exception thrown at 0x76E4B1AF (combase.dll) in copyFile.exe : 0xC0000005: Access violation reading location 0x00000008

then the program breaks.

Meanwhile, xyzCopy.txt is being created, with a fresh new modify date but as an empty file, 0 KB.

On the other hand, if I run the .exe via terminal by ./copyFile.exe, no exception is being thrown, and code execution continues to the below lines. The file xyzCopy.txt is being created, the content is full (not empty), however, the timestamp of creation is same as the original file. On contrast with the case while debugging.

Also, if CopyFile() fails, for example because of not being able to find the source file to be copied, the debugging works fine. So, the problem arises only if CopyFile() succeeds.

I have no idea what is the case. Thanks for helping.

CodePudding user response:

I could not find the root cause, however, @SimonMourier posted a link in his comments, which suggest a workaround that works.

Additional information: Toggling the debug option "Automatically close the console when debugging stops" on, stops the exception being thrown.

  • Related