0

I am trying to append some bytes to a binary file in visual c++

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <iostream>
#include <string>

//  Forward declarations:
void append(LPCTSTR);

int main()
{
    LPCTSTR fn = L"C:/kaiyin/kybig.out"; 
    append(fn);

    printf("hello world\n");
    std::string s = "";
    std::getline(std::cin, s);
    return 0;
}

void append(LPCTSTR filename) {
    LARGE_INTEGER size;
    size.QuadPart = 0;
    HANDLE fh = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    GetFileSizeEx(fh, &size);
    LPCVOID buf = "abc";
    SetFilePointerEx(fh, size, NULL, FILE_BEGIN);
    WriteFileEx(fh, buf, 3, NULL, NULL);
    CloseHandle(fh);
}

I get an error:

First-chance exception at 0x76AB8833 (KernelBase.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation reading location 0x00000008.

If there is a handler for this exception, the program may be safely continued.

What went wrong?


Update

If I run it without debugging, I get a crash report like this:

Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: ConsoleApplication1.exe
  Application Version:  0.0.0.0
  Application Timestamp:    560255b2
  Fault Module Name:    KERNELBASE.dll
  Fault Module Version: 6.3.9600.17415
  Fault Module Timestamp:   54504ade
  Exception Code:   c0000005
  Exception Offset: 000b8833
  OS Version:   6.3.9600.2.0.0.256.48
  Locale ID:    1033
  Additional Information 1: 5861
  Additional Information 2: 5861822e1919d7c014bbb064c64908b2
  Additional Information 3: a10f
  Additional Information 4: a10ff7d2bb2516fdc753f9c34fc3b069

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=280262

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt
qed
  • 22,298
  • 21
  • 125
  • 196

2 Answers2

1

Based on the msdn web site for WriteFileEx file handle used can be anything opened with FILE_FLAG_OVERLAPPED flag (which is not the case in your code). Changing this function to WriteFile works like a charm. See here for more information: WriteFileEx MSDN

AKJ88
  • 713
  • 2
  • 10
  • 20
0

I guess it's crashing because memory is not allocated to buf, buf is used without allocating memory.

Anil Kumar
  • 37
  • 8