Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c++ - Cppcheck Possible null pointer dereference:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...