Cppcheck Possible null pointer dereference:

ぐ巨炮叔叔 提交于 2019-12-08 14:24:17

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/29750481/cppcheck-possible-null-pointer-dereference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!