mercredi 12 août 2015

Pointer bounds and pointer arithmetic in SQLite source code

I was browsing through the SQLite source code when I came across this function starting at line 387 in shell.c.

Source code: http://ift.tt/1AMdXmL

The function in question:

/*
** Determines if a string is a number of not.
*/
static int isNumber(const char *z, int *realnum){
  if( *z=='-' || *z=='+' ) z++;
  if( !IsDigit(*z) ){
    return 0;
  }
  z++;
  if( realnum ) *realnum = 0;
  while( IsDigit(*z) ){ z++; }
  if( *z=='.' ){
    z++;
    if( !IsDigit(*z) ) return 0;
    while( IsDigit(*z) ){ z++; }
    if( realnum ) *realnum = 1;
  }
  if( *z=='e' || *z=='E' ){
    z++;
    if( *z=='+' || *z=='-' ) z++;
    if( !IsDigit(*z) ) return 0;
    while( IsDigit(*z) ){ z++; }
    if( realnum ) *realnum = 1;
  }
  return *z==0;
}

Note: IsDigit is a macro, which feeds an unsigned character into isdigit defined in ctype.

#define IsDigit(X)  isdigit((unsigned char)X)

The function and pointer use makes sense to me, however, the first two lines leads me to believe they may be used improperly based on my understanding.

They use pointer arithmetic to shuffle through the string.

if( *z=='-' || *z=='+' ) z++; 

If the char at the first position of the pointer is a '-' or '+', move the pointer over one position. However, this does not seem to take into account if the string passed into the function only has one character that happens to be a '-' or '+' symbol.

if( !IsDigit(*z) ){

When 'z' is dereferenced, isn't this corrupted/illegal memory access because it goes out of the bounds of the pointer, or is there something behind the scenes with pointer arithmetic that stops this from happening?

Aucun commentaire:

Enregistrer un commentaire