c++ - Efficient means of null terminating an unsigned char buffer in a string append function? -


i've been writing "byte buffer" utility module - set of functions personal use in low level development.

unfortunately, bytebuffer_append(...) function doesn't work when null terminates character @ end, and/or adds room null termination character. 1 result, when attempted, when call printf() on buffer's data (a cast (char*) performed): i'll section of string, first null termination character within buffer found.

so, i'm looking means incorporate kind of null terminating functionality within function, i'm kind of drawing blank in terms of way of going this, , use point in right direction.

here's code, if helps:

void bytebuffer_append( bytebuffer_t* destbuffer, uint8* source, uint32 sourcelength ) {     if ( !destbuffer )     {         puts( "[bytebuffer_append]: param 'destbuffer' received null, bailing out...\n" );          return;     }      if ( !source )     {         puts( "[bytebuffer_append]: param 'source' received null, bailing out...\n" );          return;     }      size_t bytelength = sizeof( uint8 ) * sourcelength;      // check see if need reallocate buffer      if ( destbuffer->capacity < bytelength || destbuffer->length >= sourcelength )     {         destbuffer->capacity += bytelength;          uint8* newbuf = ( uint8* ) realloc( destbuffer->data, destbuffer->capacity );          if ( !newbuf )         {             mem_badalloc( "bytebuffer_append - realloc" );         }          destbuffer->data = newbuf;     }      uint32 end = destbuffer->length + sourcelength;      // use separate pointer source data     // copy destination buffer      uint8* psource = source;      ( uint32 ibuffer = destbuffer->length; ibuffer < end; ++ibuffer )     {         destbuffer->data[ ibuffer ] = *psource;          ++psource;     }      // commented code below     // null termination     // happening      destbuffer->length += sourcelength; // + 1;      //destbuffer->data[ destbuffer->length - 1 ] = '\0'; } 

many providing input on this.

looks issue caused memory corruption.

you have fix following 3 problems:

1 check if allocated space enough

if ( destbuffer->capacity < bytelength || destbuffer->length >= sourcelength ) 

does not check if buffer reallocation needed, replace with

if ( destbuffer->capacity <= destbuffer->length+bytelength ) 

2 allocating enough space

destbuffer->capacity += bytelength; 

is better become

destbuffer->capacity = destbuffer->length + bytelength + 1; 

3 null terminating

destbuffer->data[ destbuffer->length - 1 ] = '\0'; 

should become

destbuffer->data[ destbuffer->length ] = '\0'; 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -