This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

strstr()


The strstr() in glibc at the moment appears to take quadratic time in the worst case. This is bad; the following little C program takes non-negligible time to execute, for instance:

#include <stdio.h>
#include <string.h>
int main() {
  char foo[77777];
  memset(foo,0,sizeof(foo));
  memset(foo,'a',77770);
  char bar[77777];
  memset(bar,0,sizeof(bar));
  memset(bar,'a',27770);
  bar[10000] = 'b';
  printf("%p\n", strstr(foo, bar));
}

The strstr() presently in glibc is a very good implementation of the naive algorithm, but, as demonstrated above, it should probably not be the default strstr() implementation in the standard C library.

I've attached a strstr() implementation that uses the present code on short patterns but switches over to a linear-time, constant-space algorithm on longer patterns. It was made against the glibc-2.3.2 package from Debian sarge. I've tested this patch extensively on both an i386 machine and an AMD64 machine, and have found no problems. (It is, of course, possible that I have overlooked all of its bugs.)

Tor Myklebust

Attachment: strstr.patch
Description: Text document


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]