[Snort-devel] Bug : misuse of calloc (patch included)

Erik de Castro Lopo erikd+snort at ...2292...
Wed Jul 28 18:38:02 EDT 2004


Hi all,

While looking around in src/sfutil/mwm.c I found a number
of instances where the calloc function was being misused,
which could lead to data alignment problems on CPU 
architectures where that can be a problem.

Calloc is defined as:

       void *calloc(size_t nmemb, size_t size);

but there are a number of places in src/sfutil/mwm.c where
it is used as:

    ptr = calloc( sizeof(SOME_STRUCT),1 );

which is asking for a pointer to sizeof(SOME_STRUCT) elements
of size one. As such, it is legal for the allocator to return
a pointer without worrying about alignment at all. Then, if
the struct contains say an int32_t, the int32_t may not be 
aligned to a four byte boundary which on some architectures 
can cause a bus fault.

Patch to fix this for src/sfutil/mwm.c included below.

Cheers,
Erik

---------------------------------------------------------------
diff -u -r1.3 mwm.c
--- src/sfutil/mwm.c    17 Dec 2003 21:25:14 -0000      1.3
+++ src/sfutil/mwm.c    29 Jul 2004 01:32:43 -0000
@@ -395,7 +395,7 @@
 */
 void * mwmNew()
 {
-   MWM_STRUCT * p = (MWM_STRUCT * )calloc( sizeof(MWM_STRUCT),1 );
+   MWM_STRUCT * p = (MWM_STRUCT * )calloc( 1, sizeof(MWM_STRUCT) );
    if( !p )
    { 
      return 0;
@@ -438,7 +438,7 @@
     MWM_STRUCT *ps = (MWM_STRUCT*)pv;
     MWM_PATTERN_STRUCT *plist=0;
 
-    MWM_PATTERN_STRUCT *p = (MWM_PATTERN_STRUCT*)calloc(sizeof(MWM_PATTERN_STRUCT),1);
+    MWM_PATTERN_STRUCT *p = (MWM_PATTERN_STRUCT*)calloc(1,sizeof(MWM_PATTERN_STRUCT));
 
     if( !p ) return -1;
 
@@ -1253,12 +1253,12 @@
    MWM_PATTERN_STRUCT * plist;
 
    /* Build an array of pointers to the list of Pattern nodes */
-   ps->msPatArray = (MWM_PATTERN_STRUCT*)calloc( sizeof(MWM_PATTERN_STRUCT), ps->msNumPatterns );
+   ps->msPatArray = (MWM_PATTERN_STRUCT*)calloc( ps->msNumPatterns, sizeof(MWM_PATTERN_STRUCT) );
    if( !ps->msPatArray ) 
    { 
         return -1; 
    }
-   ps->msNumArray = (unsigned short *)calloc( sizeof(short), ps->msNumPatterns  );
+   ps->msNumArray = (unsigned short *)calloc( ps->msNumPatterns, sizeof(short) );
    if( !ps->msNumArray ) 
    { 
         return -1; 
---------------------------------------------------------------




-- 
------------------------------------------------------
[N] Erik de Castro Lopo, Senior Computer Engineer
[E] erik.de.castro.lopo at ...2292...
[W] http://www.sensorynetworks.com
[T] +61 2 83022726 
[F] +61 2 94750316 
[A] L4/140 William St, East Sydney NSW 2011, Australia
------------------------------------------------------
A good debugger is no substitute for a good test suite.




More information about the Snort-devel mailing list