Bad pointers and invalid memory access in C

But you need to be very careful with the pointers while using them. Pointers can make your system crash and corrupt memory locations if not handled properly. When pointers are incremented or decremented to point to next or previous memory locations, they may be pointing to invalid memory locations which when read or written to may cause serious problems.

The most common mistake is using an uninitialized pointer. Its always a best practice to initialize a pointer to NULL value when they are declared and check for whether the pointer is a NULL pointer when using the pointer.

i.e., if you declare a pointer and dont yet know where to point the pointer, then initialize the pointer to NULL.

unsigned char *pData =  NULL; // NULL is a common keyword and is always #defined to zero. inside the compilers header files.

So when you make a read or write access to the pointer then make a check like,

if( pData != NULL )

{

*pData = value;

}

This way you can avoid accessing an invalid uninitialized pointer. The most common symptoms of a bad pointer is the microcontroller going into an unknown state if the pointer corrupts the stack memory of the microcontroller which holds the return addresses.

Leave a Comment

Your email address will not be published. Required fields are marked *