Cppcheck Possible null pointer dereference:
Asked Answered
S

2

-6

i am just using cppcheck the code is working properly just cppcheck gives this errors.

void WorkerThread(WorkBuffer* m_buffer)
{
    std::cout << "Thread : " << m_buffer->m_id << ".....Starting" << std::endl;

    if (NULL == m_buffer)
        std::cout << "Thread : " << m_buffer->m_id << "......work buffer is null" << std::endl;


    while(!shut_down_flag)
    {
        int k = 0;
        //Sleep(1);
        SleepSystemUsec(100000);
        std::cout << "Thread : " << m_buffer->m_id << "....in while loop" << std::endl;
    } // of while(!shut_down_flag)

    std::cout << "Thread : " << m_buffer->m_id << ".....Request from main thread so ending working thread ...." << std::endl;
};

error : : Possible null pointer dereference: m_buffer - otherwise it is redundant to check it against null.

Sicklebill answered 20/4, 2015 at 14:20 Comment(3)
More code please & CPPCheck command line options supplied.Sabbatarian
You're checking if m_buffer is NULL after you've already used it. The message is pointing out (correctly) that if it could be NULL (and if not, why are you checking?) you should find out before using it in the line above.Octroi
@PaulRoub: That should be an answer not a comment.Quarles
T
5
if (NULL == m_buffer) 

makes sure m_buffer is NULL, and then you derefence it with

std::cout << "Thread : " << m_buffer->m_id << "......work buffer is null" << std::endl;
                            ^^^^^^^^^^^^^^^

this, which is only legal if m_buffer is not NULL (more precisely, only if it points to a correctly constructed WorkBuffer).

If NULL is a possible input for your function, you need to check for it before the very first dereference and then either make it point to something valid or leave the function without dereferencing.

Tosh answered 20/4, 2015 at 14:24 Comment(4)
couldn get what you said. would you please provide some detailsSicklebill
@Sicklebill Could you be a little bit more specific with what you don't get?Tosh
In fact, the cppcheck warning is for the previous m_buffer->m_id << ".....Starting" before the check. It doesn't spot this error.Peeved
@Peeved Well this is the same problem as the other one (covered by my "check for it before the very first dereference " remark): Either the pointer can be NULL, then check before you use it, or it cannot, then you never need to check.Tosh
Q
0

Not only is your condition backwards:

if m_buffer is NULL:
  do things that dereference m_buffer
(huh?!)

but you have no checks on any of the other output statements.

Quarles answered 20/4, 2015 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.