Question

Problem

I have been trying all sorts of byte counts trying to get WriteFile to work. The problem is it immediately crashes after writing to the file. All the text is in the file but yet the "A program has crashed, send to Microsoft??" Error Dialog pops up.

When commenting out invoke WriteFile and everything below it, the program runs fine and does not crash. However when I just uncomment WriteFile and leave all the code below it commented out it again rears it's ugly head. The code is below and if anybody can see something that I missed it is much appreciated :-)

Byte Lengths I have tried.

I have tried byte lengths of 23, 24 (string length + null), 25 (Maybe I forgot a byte), and also just using SIZEOF WriteText and all of them failed :-(.

Code

.386 
.model flat,stdcall 
option casemap:none ; Case Sensitive

; Windows
include \masm32\include\windows.inc 

; Kernel32
include \masm32\include\kernel32.inc 
includelib \masm32\lib\kernel32.lib 

.data 
FilePath         db "C:\test.txt",0
WriteText        db "This is some test text."

.code 
start: 

; Edit a file

invoke CreateFile, addr FilePath, GENERIC_WRITE, FILE_SHARE_WRITE or FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL
push eax ; save the file handle

; This works other than the crashing, any number less then 23
; and the file has some of the text clipped
; any larger and NUL is appended until the byte count is matched.
invoke WriteFile, eax, addr WriteText, 23, NULL, NULL

pop eax
push eax

invoke CloseHandle, eax

invoke ExitProcess, 0
end start 
Was it helpful?

Solution

According to the documentation for the WriteFile function:

lpNumberOfBytesWritten [out, optional]
[...]
This parameter can be NULL only when the lpOverlapped parameter is not NULL.

You have both lpNumberOfBytesWritten and lpOverlapped as NULL. Pass addr some_writable_variable as lpNumberOfBytesWritten and it should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top