Bridgey
Bridgey

Reputation: 539

Why does this use of fscanf cause the application to crash?

New to C programming.

The following section of code attempts to read a tab-separated list of MD5 (32 chars) and corresponding description (up to 128 chars) from a text file (utf-8), but is causing the application to crash:

HANDLE hFile = CreateFileW(good_path, GENERIC_READ, FILE_SHARE_READ, NULL,
    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
    return FALSE;
}

LPWSTR md5 = malloc(sizeof(wchar_t) * 32);
LPWSTR desc = malloc(sizeof(wchar_t) * 128);
int i;
while((i = fwscanf(hFile, L"%ls %ls", md5, desc)) != EOF)
{
    if (i == 2) // OK
    {
    }
    else // Something went wrong
    {
    }
}
CloseHandle(hFile);
return TRUE;

Few questions:

  1. Is my use of malloc(...) correct?
  2. What might be causing the crash?

Update 1

I've taken this code and made it into a standalone exe (rather than a DLL). Still crashes.

Update 2

Updated to fwscanf as per Chris's comment. Still crashes. If I comment out the while...fwscanf... line it exits properly.

Upvotes: 1

Views: 173

Answers (3)

AlexP
AlexP

Reputation: 4430

CreateFileW() returns a Windows handle, which is sort of like a file number but different somehow. fwscanf() expects a FILE* not a Windows handle; to get a FILE* open your file with fopen() or _wfopen().

Upvotes: 3

szpanczyk
szpanczyk

Reputation: 488

%s stores a nul-terminated string under the address your provide. To store n significant characters without buffer overflow, you need to provide an address of n+1 long buffer.

Upvotes: 0

Mischa
Mischa

Reputation: 2298

  1. %s stores a null terminator. Malloc 33 and 129 chars.

Upvotes: 0

Related Questions