Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

c++ - WriteConsole access violation in function call but not from 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
");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This declaration is wrong:

LPDWORD charsWriten;

The CreateFile function expects the fourth parameter to be a pointer to a variable it can write into. You don't actually allocate memory, though; you just declare a pointer—an uninitialized one at that. That won't work. You need to do:

DWORD charsWritten;

...

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

That will fix the access violation problem, but it doesn't explain why you are writing one character past the end of your string. You don't need to add 1 to strlen; the terminating NUL doesn't need to be written.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...