Stefana Fratean
Stefana Fratean

Reputation: 164

Access violation reading location 0xfeeefef2 multithreaded programming c++ windows

I have this code that does the following:

-generates a linked list that contains "e" nodes, each node has assigned a random value, and worker number

-creates w threads, each thread ckecks in the list if the worker number of the node is equal to his thread id, if so, it makes sqrt from the value

-when 5 or all of the values from the list are smaller than 2, the main thread deletes from the list the elements smaller than 2

-only 3 threads can work at once.

Here is the code:

DWORD WINAPI work(LPVOID argument){
    int tid = *((int *)argument);
    elem* p = head;
    while(p!=NULL){
        if (tid == p->worker){
            WaitForSingleObject(semaphor, 0L);
            double val = p->value;
            p->value = sqrt(val);
            if (p->value < 2){
                EnterCriticalSection(&countMutex);
                count++;
                if(count == maxCount){
                    WakeConditionVariable (&conditionalVar);
                }
                LeaveCriticalSection(&countMutex);
            }       
            Sleep(1);
            ReleaseSemaphore(semaphor, 1L, NULL);
        }
        if (p->next == NULL)
            p = head;
        else 
            p = p->next;
    }

    return NULL;
}

int _tmain(int argc, _TCHAR* argv[])
{
    //generate list, create threads (the threads are assigned to the work function)

    EnterCriticalSection(&countMutex);
    while(e > 0){
        SleepConditionVariableCS(&conditionalVar, &countMutex, INFINITE);
        deleteElements();
        if (e < 5)
            maxCount = e;
        count = 0;
        cout << "After erasure: \n";
        printList();
        cout << "\n";
    }
    LeaveCriticalSection(&countMutex);


    //free space
}

The problem is that after the first deletion, i get the error "Unhandled exception at 0x00fe1c8e in mainW.cpp.exe: 0xC0000005: Access violation reading location 0xfeeefef2."

I do realise that this means that somewhere i'm trying to acces a value that has already been deleted, but i don't know why, since the list is synchronized.

Upvotes: 0

Views: 1635

Answers (1)

Bo Persson
Bo Persson

Reputation: 92261

You are traversing the list without any locks.

if (p->next == NULL)
    p = head;
else 
    p = p->next;

What if the main thread just deleted p->next?

Upvotes: 2

Related Questions