Archived

This topic is now archived and is closed to further replies.

Checking overflow in strings

This topic is 6017 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How can I check for overflows and prevent them with character arrays/strings?

Share this post


Link to post
Share on other sites
If you want to find out how big a string is, use strlen(). This returns the number of characters in the string, not including the terminating zero.
To concatenate one string with a second, and limit the number of characters to copy, use strncat(). So you could use a limit like (MAX_LEN-strlen(string)-1), if MAX_LEN is the size of the character array (aString[MAX_LEN]).

A lot of the string manipulation routines are str[n][action]. If the n is there, there will be a parameter to limit the number of characters.

Share this post


Link to post
Share on other sites
By "overflow", I assume you mean writing outside the boundaries of your array. One way to prevent this is to place sentinels on the boundaries of your array. By sentinel I just mean a unique value; when you free your array, you can check to see if it's been overwritten. The code below will use 3 S's as a sentinel:


#define SENTINEL ('S')

char* MyMalloc( unsigned int Size )
{
#if DEBUG
char* pMem;
char* pUserMem;
unsigned int PaddedSize = 3 + Size + 3;

pMem = (char*)malloc( PaddedSize );

SetMemBlockSize( pMem, PaddedSize );

pMem[0] = pMem[1] = pMem[2] = SENTINEL;
pMem[PaddedSize-1] = pMem[PaddedSize-2] = pMem[PaddedSize-3] = SENTINEL;

pUserMem = pMem + 3;
return( pUserMem );
#else
return( (char*)malloc( Size ) );
#endif
}

void MyFree( char* pUserMem )
{
#if DEBUG
char* pMem = pUserMem - 3;
unsigned int PaddedSize = GetMemBlockSize( pMem );

if( pMem[0] != SENTINEL ||
pMem[1] != SENTINEL ||
pMem[2] != SENTINEL )
{
printf( "invalid memory write: behind start of array" );
}
if( pMem[PaddedSize-1] != SENTINEL ||
pMem[PaddedSize-2] != SENTINEL ||
pMem[PaddedSize-3] != SENTINEL )
{
printf( "invalid memory write: beyond end of array" );
}

free( pMem );
#else
free( pUserMem );
#endif
}

void main(void)
{
char* Str;

Str = MyMalloc( 4 );

strcpy( Str, "hello" );

// will print "invalid memory write: beyond end of array" in a debug build
MyFree( Str );
}


A few things: Out-of-bounds checking is not necessary once your program is complete (release builds). Since you're only doing the checking for debug builds, it doesn't really matter how much memory you waste on the sentinel -- use 16 bytes, 256 bytes, whatever. Also, yes, I was too lazy to actually define SetMemBlockSize and GetMemBlockSize.

Edited by - Eric on July 29, 2001 5:41:15 AM

Share this post


Link to post
Share on other sites