Weird access violations

[code]
// Loads data/text from a file into an editbox control
BOOL LoadFileToEdit(HWND hEdit, LPSTR filePath)
{
HANDLE hFile = NULL;
LPSTR text;
DWORD dwSize = NULL;
BOOL bResult = FALSE;

hFile = CreateFile(
filePath, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
dwSize = GetFileSize(hFile, &dwSize);
if (dwSize) {
text = (LPSTR) GlobalAlloc(GPTR, dwSize + 1);
if (text) {
DWORD dwRead;
if (ReadFile(hFile, text, dwSize, &dwRead, NULL)) {
SetWindowText(hEdit, text);
bResult = TRUE;
}
GlobalFree(text);
}
}
CloseHandle(hFile);
}
return bResult;
}[/code]

Okay, so that function (to me) looks perfectly acceptable, given its simplicity. And it works almost all the time, but it randomly throws out an un-handle-able access violation every now and again. I can't for the life of me figure out why.

Can anyone here give me some tips? And yes, I am relatively new to the win32 API (in case it's painfully obvious by the above code :P).

Comments

  • : [code]:
    : // Loads data/text from a file into an editbox control
    : BOOL LoadFileToEdit(HWND hEdit, LPSTR filePath)
    : {
    : HANDLE hFile = NULL;
    : LPSTR text;
    : DWORD dwSize = NULL;
    : BOOL bResult = FALSE;
    :
    : hFile = CreateFile(
    : filePath, GENERIC_READ, FILE_SHARE_READ, NULL,
    : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    : if (hFile != INVALID_HANDLE_VALUE) {
    : dwSize = GetFileSize(hFile, [color=Blue]NULL[/color]);
    : if ([color=Blue]dwSize > 0[/color]) {
    : text = (LPSTR) GlobalAlloc(GPTR, dwSize + 1);
    : if (text) {
    : DWORD dwRead;
    : if (ReadFile(hFile, text, dwSize, &dwRead, NULL)) {
    [color=Blue]text[dwRead] = '';[/color]
    : SetWindowText(hEdit, text);
    : bResult = TRUE;
    : }
    : GlobalFree(text);
    : }
    : }
    : CloseHandle(hFile);
    : }
    : return bResult;
    : }[/code]:
    :
    : Okay, so that function (to me) looks perfectly acceptable, given its
    : simplicity. And it works almost all the time, but it randomly throws
    : out an un-handle-able access violation every now and again. I can't
    : for the life of me figure out why.
    :
    : Can anyone here give me some tips? And yes, I am relatively new to
    : the win32 API (in case it's painfully obvious by the above code :P).
    :

    I made some changes in blue. They are probably the fix. Specifically, you forgot to 0-terminate your string.
    Also, GlobalAlloc seems a bit unnecessary here. You're probably safer of using new/delete or malloc/free.



    Best Regards,
    Richard

    The way I see it... Well, it's all pretty blurry
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion