函数调用中的WriteConsole访问冲突,但不是来自main() [英] WriteConsole access violation in function call but not from main()

查看:147
本文介绍了函数调用中的WriteConsole访问冲突,但不是来自main()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在函数调用中使用WriteConsole(..),但是出现访问冲突。当我在main中取消注释代码时,它将主要功能中的文本打印到屏幕上,没有任何问题。当我尝试在函数调用中打印字符串时,即使它将文本打印到控制台,也会遇到访问冲突。

I am trying to use WriteConsole(..) in a function call but I get access violation. When I un-comment the code in main, it prints my text to the screen with no problem in the main function. When I try to print the string in the function call I get access violation even though it does print the text to the console.

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 Failed\n");
    }
}


推荐答案

LPDWORD charsWriten;

LPDWORD DWORD * 。所以你有什么是一个未初始化的指针。然后您将该指针传递给 WriteConsole ,该指针写入指向的无效位置。相反,将 charsWritten 声明为 DWORD ,并将其地址传递给 WriteConsole & charsWritten 。

LPDWORD is DWORD*. So what you have there is an uninitialized pointer. You then pass this pointer to WriteConsole, which writes to the invalid location pointed to. Instead, declare charsWritten as type DWORD, and pass its address to WriteConsole with &charsWritten.

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

如您所说,如果它在main中有效,这只是运气不好。这是未定义的行为,并不总是有可预见的结果。

If, as you say, it works as you have it in main. That is simply bad luck. It's undefined behavior, which doesn't always have predictable results.

这篇关于函数调用中的WriteConsole访问冲突,但不是来自main()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆