background image
<< Bugs with Pointers and Memory | Synchronization Errors >>

NULL dereferencing

<< Bugs with Pointers and Memory | Synchronization Errors >>
c h a r * foo (){
c h a r ch ;
// s o m e o p e r a t i o n s
r e t u r n (& ch );
/* l o c a l v a r i a b l e f r om the s t a c k is r e t u r n e d */
}
2.1.3
Free the already freed resource
(frequent, major) [26]
This a common form of error where the programmer tries to free the already freed resource. In
general the resources are first allocated and then freed. For example, memory is first allocated and
then deallocated. So we should not try to free the already freed resource.
m a i n (){
c h a r * str ;
str =( c h a r *) m a l l o c ( 1 0 ) ;
if ( g l o b a l = = 0 )
f r e e ( str );
// S o m e s t a t e m e n t s
f r e e ( str ); /* H e r e str is a l r e a d y f r e e d
* on t r u e b r a n c h */
}
This may be more erroneous, if we have some malloc statement between the two free statements.
There is a chance that the first freed locations are now allocated to the new variable. And the
subsequent free will deallocate the new variable. Hence dereferencing it may cause runtime error.
2.1.4
NULL dereferencing
(frequent, catastrophic) [13]
Improper initialization and missing the initialization in different paths leads to the NULL refer-
ence error. This can also be caused because of aliases (two variables refer to the same object, and
one is freed and an attempt is made to dereference the second variable).
To dereference a memory location, it should be initialized first and then dereferenced. The
following code pattern illustrates NULL dereference bug.
c h a r * ch = N U L L ;
if ( x > 0 ) {
ch = ' c ';
}
p r i n t f ( " \ % c " , * ch );
// ch may be N U L L
Whenever an object is being dereferenced, take care to see that it has been initialized in all
possible paths to the point of dereferencing. Missing the initialization in any path may cause this
error on some input value, which follows this control path.
2.1.5
Exposure of private data to untrusted components
(rare, catastrophic) [26]
Sometimes it is most important to preserve the integrity and security of data. The data which
is supposed to be private should not be given access to external sources. The following example
illustrates this fact.
3