[英]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. 我试图在函数调用中使用WriteConsole(..),但遇到访问冲突。 When I un-comment the code in main, it prints my text to the screen with no problem in the main function.
当我取消注释main中的代码时,它将我的文本打印到屏幕上,而main函数没有问题。 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");
}
}
This declaration is wrong: 该声明是错误的:
LPDWORD charsWriten;
The CreateFile
function expects the fourth parameter to be a pointer to a variable it can write into. CreateFile
函数期望第四个参数是指向它可以写入的变量的指针。 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
; 您不需要在
strlen
上加1; the terminating NUL doesn't need to be written. 不需要编写终止的NUL。
LPDWORD charsWriten;
LPDWORD
is DWORD*
. LPDWORD
是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. 然后,您将此指针传递给
WriteConsole
,该指针将写入指向的无效位置。 Instead, declare charsWritten
as type DWORD
, and pass its address to WriteConsole
with &charsWritten
. 而是将
charsWritten
声明为DWORD
类型,并使用&charsWritten
将其地址传递给WriteConsole
。
DWORD charsWritten;
WriteConsole(hFile, text, (strlen(text) + 1), &charsWritten, NULL);
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.
这是不确定的行为,并不总是可以预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.