开发者

Access Violation when calling LockFileEx()

开发者 https://www.devze.com 2023-04-11 20:46 出处:网络
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().

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;
}

Whenev开发者_如何转开发er 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号