Question

I have a FileMapping class that allows me to also lock a file for exclusive use by my process by using the Win32 API function LockFileEx().

bool FileMapping::lockFile(bool wait) {
    if (isFileLocked())
        return true;

    // We want an exclusive lock.
    DWORD flags = LOCKFILE_EXCLUSIVE_LOCK;

    // If we don't want the thread to block, we have to set the appropriate flag.
    if (!wait)
        flags |= LOCKFILE_FAIL_IMMEDIATELY;

    m_isFileLocked = LockFileEx(m_fileDesc, flags, 0, (DWORD) m_mappingLength, (DWORD) (((uint64_t) m_mappingLength) >> 32), NULL);
    return m_isFileLocked;
}

Whenever I get to the LockFileEx() call I get an access violation:

Unhandled exception at 0x7466c2ec in tftpServer.exe: 0xC0000005:
Access violation reading location 0x00000008.

The file handle m_fileDesc is definitely a valid handle (mapping the file into memory with that handle works) and m_mappingLength is just a size_t containing the length of the mapped file portion in bytes.

Does anybody have an idea how to fix this?

Was it helpful?

Solution

Your last argument is NULL, while it should be a pointer to a OVERLAPPED structure. The error about reading location 0x00000008 probably corresponds to the documented requirement that:

You must initialize the hEvent member to a valid handle or zero.

Given the hEvent member comes after two pointers, in 32 bit compilation it'd be 8 bytes from the beginning of the structure. So LockFileEx is probably trying to read the hEvent member, and crashes.

OTHER TIPS

Quoting the docs you link to:

lpOverlapped [in, out]

A pointer to an OVERLAPPED structure that the function uses with the locking request. This structure, which is required, contains the file offset of the beginning of the lock range. You must initialize the hEvent member to a valid handle or zero.

So your last argument is wrong.

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