Home > Software design >  CPPCheck Null pointer dereference
CPPCheck Null pointer dereference

Time:12-09

I maintain some embedded C code (No OS). I have made some updates an run CPPCheck on my changes.

CPPCheck has brought up the error 'Null pointer dereference: (volatile unsigned int*)0'. This is not in my code changes but I am keen to understand what is going on. As far as I understand the behaviour of dereferencing a null pointer is undefined.

'''

typedef void (*pfFunc_T)( void );

/* restart bootloader */
pfFunc_T  pfFunc;

__interrupt_disable();

pfFunc  = (pfFunc_T)( ( *(volatile U32*)0 ) );   /*CPPCheck error*/

if ( pfFunc != NULL )           /* no program loaded */
{
    pfFunc();
}

'''

It is memory mapped and the boot loader is first. Could it be calling the boot loader from a different application?

CodePudding user response:

I guess that you are trying to assign a function pointer to contents found at memory address zero. This won't work with a conforming compiler - the C language doesn't allow access to absolute address zero, since that one is reserved for the special case of null pointers.

To solve this you need to have some manner of identifier linked to address zero, then use that identifier in your source.

CodePudding user response:

The definition of NULL (pointer) looks usually like this:

#define NULL  ((void*)0)

So, your code here:

pfFunc  = (pfFunc_T)( ( *(volatile U32*)0 ) );   /*CPPCheck error*/
                        ^-- (1)

dereferences the NULL pointer due to the asterisk at (1).

You would initialize the pFunc like this:

pfFunc  = (pfFunc_T)( ( (volatile U32*)0 ) );
//                     ^-- no * here

or just use this form without explict cast

pfFunc  = NULL;
  • Related