I am trying to implement a strnstr function into C (strstr but it checks the length), for some reason it doesn't work (output is always no):
#include <stdio.h>
char *searchingFor = "stackdummy";
char *in = "la da\ndoo a da\nnow here comes the stack\nok there it was.\n";
char *strnstr(char *s1, char *s2, int length) {
if(s1 == NULL || s2 == NULL) return NULL;
printf("searching \n\n\"%s\"\n for %.*s\n", s1, length, s2);
char *ss1 = malloc(strlen(s1) + 1);
strcpy(ss1, s1);
char *ss2 = malloc(length + 1);
strncpy(ss2, s2, length);
char *result = strstr(ss1, ss2);
free(ss1);
free(ss2);
return result;
}
int main(void) {
printf("found: %s\n", strnstr(in, searchingFor, 5) ? "yes" : "no");
printf("found: %s\n", strnstr(in, searchingFor, 5) ? "yes" : "no");
printf("found: %s\n", strnstr(in, searchingFor, 5) ? "yes" : "no");
return 0;
}
The implementation provided by Chris Dodd has the following disadvantages:
strnstr
in that thewhile
condition uses the unbounded string functionstrchr
haystack
being NULL terminated, which is a deviation from the usual implementation ofstrnstr
, for example as provided by GNU-Darwinstrchr
is an unnecessary function call whenstrchar
is not inlinedhaystack
instead ofNULL
whenlen
is zero, a deviation from the acceptedstrstr
semanticshaystack
whenneedle
has length of zeroThe following implementation remedies the above problems without becoming as difficult to read as the GNU-Darwin implementation, and is Creative Commons licensed:
How about:
If you want
haystack
to not be null terminated, you'll need two length args:which is available in GNU libc, though older versions are broken.