Search code examples
cvalgrind

Invalid read of size 1 in while loop condition


I recently inherited code, written in C, without any documentation. I've been working at optimizing and fixing it and I've come across this.

int  LookBack(char * Start, int Length, char *Ignore)
{
  char  LookBuffer[10];
  //while(Start[-1] && Length--) Start--; // Start[-1]. No idea what that is supposed to mean.
  while(Length > 0 && Start[0]){
    Start--;
    Length--;
  }
  strncpy(LookBuffer, Start, sizeof(LookBuffer));
  if(strcasestr(LookBuffer, Ignore)) {
    return(1);
  }
  return(0);
}

This function is used to determine if a substring is a certain distance in front of the string Start. For example, take the string The designation is API RP 5L1 and Start is a pointer to API RP 5L1. So, if Ignore = "The" and Length = 10, the function will return 0.

My Question

Valgrind gives me the Invalid read of size 1 error because it is reading past the allocated memory at while(Length > 0 && Start[0]), or so I believe. Is there any way I can check that Start[0] is in allocated memory without doing an invalid read?


Solution

  • For C functions that are working with memory buffers, it is caller responsibility to pass valid pointers. There might be some platform-specific trick, but in terms of standard C there's no way, as well as for many platforms (for example just-freed memory is often indistinguishable from still allocated).