[Home]CharacterArraysInC

TheSourcery | RecentChanges | Preferences | Index | RSS

Difference (from prior major revision) (no other diffs)

Removed: 85d84
[custom research papers]

A reliable way to handle character arrays in C and C++

A typical problem encountered in C and C++ is character buffer overflows, or reading and writing past the end of an array, or working with arrays that for some reason are not NUL terminated or contain NULs (i.e. network streams and binary files). In C++ programming the string class is generally the preferred mechanism used to construct arrays of characters but it crops up from time to time.

Both the C and C++ standards provide a special pointer just for this purpose. Much like the

null pointer it is invalid to dereference but okay to use in pointer comparisons. But unlike null pointer one can do legal pointer arithmetic with it. That is to say its behavior is well-defined by the standards.

Every array has a just past the end of the array pointer. The idiom that follows should be familiar to C++ programmers as it is used extensively throughout the STL by containers and iterators. This applies to all arrays, whether they contain characters, integers, or structures.

Given a character array...

 char buffer[256];

One can define two pointers to it. One set to the beginning and one set to the end of array pointer.

 char * start_array_ptr = buffer;

 char * end_array_ptr = start_array_ptr + 256;   

It's important to note that the following has undefined behavior per the standards.

 start_array_ptr + 257;

With that in mind, the proper way to prevent buffer overflows and other head-slapping

errors and mistakes in C and C++ is to always to pass this pointer along with a character

array to functions that will modify it.

 foo (const char* txt) {

  buffer[256];

  html_colorconv2(buffer, buffer+256, txt);

 }

 void html_colourconv2( char *buffer, const char* eob, const char *txt ) {

   const  char *point;

   for( point = txt ; *point ; point++ ) {

     *buffer = *point;

     ++buffer;   

     if (buffer == eob) {

        /* however you wish to handle it */

        printf("buffer overflow"); 

        --buffer;

        *buffer = '\0';

        break;

     }

   }

 }


TheSourcery | RecentChanges | Preferences | Index | RSS
Edit text of this page | View other revisions
Last edited March 2, 2011 11:35 am by Tyche (diff)
Search:
All material on this Wiki is the property of the contributing authors.
©2004-2006 by the contributing authors.
Ideas, requests, problems regarding this site? Send feedback.