Dereferencing a NULL pointer in embedded

1k Views Asked by At

I am using Renesas V850 series microcontroller in my project. My product uses a Non-Volatile memory blocks(NVRam blocks) location which is separate from the main program section. During runtime, these NVRam blocks are monitored to verify that they are not corrupted. This check is done with a code similar to given below:

Logic 1

if((NULL != pBlock_One_Pointer) &&  (BLOCK_ONE_ID != *(((const tUI8*)pBlock_One_Pointer) + ID_OFFSET))) 
{
.....Do some corrective action....
}

The problem with this code is , if pointer "pBlock_One_Pointer" somehow gets corrupted with value "NULL" , the Block_ID check(2nd portion of "if" statement is not done).

One way to avoid this situation is to remove the first part of "if" condition where it checks the Block_ID irrespective of pointer is "NULL" or not as given below

Logic 2

if (BLOCK_ONE_ID != *(((const tUI8*)pBlock_One_Pointer) + ID_OFFSET))

But if "pBlock_One_Pointer" points to NULL, will it cause a exception ?

So basically I have 2 questions:

  1. Is there a chance that pointer becomes NULL pointer due to some corruption during runtime?
  2. If so , will Logic 2 help me to overcome it?
2

There are 2 best solutions below

1
On

But if "pBlock_One_Pointer" points to NULL, will it cause a exception ?

It causes undefined behavior.

Per 6.5.3.2 Address and indirection operators of the C standard:

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object.
If the operand has type ‘‘pointer to type ’’, the result has type ‘‘ type ’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

So:

Is there a chance that pointer becomes NULL pointer due to some corruption during runtime?

Yes. It's possible.

If so , will Logic 2 help me to overcome it?

No. How could it? The location of the memory you want to check for corruption is lost.

0
On

Is there a chance that pointer becomes NULL pointer due to some corruption during runtime?

Yes, there are several things that could cause this. Software issues such as pointer bugs, runaway code, stack overflow etc. And in addition, failing memory hardware because of data retention, EMI (nowadays less likely) or ambient radiation/cosmic rays.

If so , will Logic 2 help me to overcome it?

No. There are ways to detect corrupt RAM, most commonly CRC checksums.

To detect failing memory hardware, there are other ways like "walking patterns" where you cycle cells by writing 1 and 0 to them at regular intervals. In modern embedded systems however, memory with built-in ECC is used, so that the software need not bother about memory hardware integrity.