C++调试断言失败,使用Windows.h互斥

C++ Debug assertion failed, using Windows.h mutex

本文关键字:Windows 互斥 使用 调试 断言 失败 C++      更新时间:2023-10-16

我有一个由以下代码引起的问题:

char KernelFS::mount(Partition* part) {
WaitForSingleObject(mutexFS,INFINITE);
int pos;
for(pos=0; pos<26; pos++)
    if(mountedPartitions[pos] == 0)
        break;
if(pos < 26) {
    mountedPartitions[pos] = part;
    bitVectors[pos] = new BitVector(part);
    fileEvidention[pos] = new ListHandler();
    openedFiles[pos] = 0;
    forbidOpening[pos] = false;
    ReleaseMutex(mutexFS);
    return intToChar(pos);
}
else {
    ReleaseMutex(mutexFS);
    return '0';
}

}

char KernelFS::format(char部分){

WaitForSingleObject(mutexFS,INFINITE);
forbidOpening[charToInt(part)] = true;
ReleaseMutex(mutexFS);
while(openedFiles[charToInt(part)]>0)
    WaitForSingleObject(unmountSem,INFINITE);

WaitForSingleObject(mutexFS,INFINITE);
//  write fresh bit vector to cluster 0 of partition
bitVectors[charToInt(part)]->formatBitVector();
openedFiles[charToInt(part)] = 0;
forbidOpening[charToInt(part)] = false;
delete fileEvidention;    //!!***!!
fileEvidention[charToInt(part)] = new ListHandler();
// some other stuff, irrelevant
ReleaseMutex(mutexFS);
return 1;

}

有3个线程正在执行,1个线程被阻塞,2个线程正在运行此代码;它们首先调用mount,然后调用format(每个都有自己的参数Partition object,p1和p2)。第一次调用mount时,它总是通过——然后在两个运行线程中的任何一个下一次调用mount/format时,都会随机出现断言失败。

通常,它在线程1期间失败-它调用mount(..)完成它,然后调用format(..),然后失败:delete fileEvidention[charToInt(pos)];(在调试模式下,当我到达该指令时,即使我尝试使用F11,也会出现断言失败)

如果重要的话。。。这是初始化:

char KernelFS::firstLetter = 'A';                   //  'A' = 65
Partition* KernelFS::mountedPartitions[26] = {0};   //  init. no partitions are mounted
BitVector* KernelFS::bitVectors[26] = {0};          //  init. no partitions are mounted
bool KernelFS::forbidOpening[26] = {false};
long KernelFS::openedFiles[26] = {0};
ListHandler* KernelFS::fileEvidention[26] = {0};
HANDLE KernelFS::mutexFS = CreateMutex(0,0,0);
HANDLE KernelFS::unmountSem = CreateSemaphore(0,0,INFINITE,0);

我以前从未遇到过这个错误,我不知道如何调试,也不知道是什么原因导致的。提前感谢您的帮助。

编辑:当我删除标记的代码行(并忽略内存泄漏)时,没有断言失败。这是什么魔法?

!:)

已解决。应该是delete fileEvidention[charToInt(part)];……