WriteConsole访问在功能调用中违反,而不是来自main()

WriteConsole access violation in function call but not from main()

本文关键字:main 功能 访问 调用 WriteConsole      更新时间:2023-10-16

我试图在函数调用中使用WriteConsole(..(,但我受到访问违规。当我以主机为单位时,它将我的文本打印到屏幕上,在主函数中没有任何问题。当我尝试在函数调用中打印字符串时,即使它确实将文本打印到控制台。

void print(char *_charArray);
int _tmain(int argc, _TCHAR* argv[])
{
    HWND hConsole;
//    HANDLE hFile;
    char myText[] = "This is my text";
    char *pMyText = myText;
    LPDWORD charsWriten;

//    hFile = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_READ, NULL,
//        OPEN_EXISTING, 0, NULL);
    print(pMyText);
//    WriteConsole(hFile, myText, sizeof(myText), charsWriten, NULL);

    getch();
    return 0;
}
void print(char *text)
{
    LPDWORD charsWriten;
    HANDLE hFile;
    hFile = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE,
                    FILE_SHARE_WRITE | FILE_SHARE_READ, NULL,
                    OPEN_EXISTING, 0, NULL);
    unsigned int strn = strlen(text) + 1;
    if(!WriteConsole(hFile, text, (strlen(text) + 1), charsWriten,NULL))
    {
        printf("Write Failedn");
    }
}

此声明是错误的:

LPDWORD charsWriten;

CreateFile函数期望第四参数是可以写入变量的指针。但是,您实际上并没有分配内存;您只是声明了一个指针,这是一个非专业化的指针。那行不通。您需要做:

DWORD charsWritten;
...
WriteConsole(hFile, text, (strlen(text) + 1), &charsWritten, NULL)

将解决访问违规问题,但它并不能解释为什么您要在字符串末端编写一个字符。您无需将1添加到strlen;终止不需要编写。

LPDWORD charsWriten;

LPDWORDDWORD*。因此,您拥有的是一个非初始化的指针。然后,您将此指针传递给WriteConsole,该指针将其写入指向的无效位置。相反,将charsWritten声明为类型DWORD,并使用&charsWritten将其地址传递给WriteConsole

DWORD charsWritten;
WriteConsole(hFile, text, (strlen(text) + 1), &charsWritten, NULL);

,如您所说,它可以正常工作。那简直是厄运。这是不确定的行为,并不总是具有可预测的结果。

相关文章: