Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 10 Oct 2001 20:16:27 +0400 (MSD)
From:      "Andrew L. Neporada" <andrew@nas.dgap.mipt.ru>
To:        Mike Barcroft <mike@FreeBSD.ORG>
Cc:        audit@FreeBSD.ORG
Subject:   Re: strnstr(3) - New libc function for review
Message-ID:  <Pine.BSF.4.21.0110101958250.51458-200000@nas.dgap.mipt.ru>
In-Reply-To: <20011010115210.E49828@coffee.q9media.com>

next in thread | previous in thread | raw e-mail | index | archive | help

[-- Attachment #1 --]
On Wed, 10 Oct 2001, Mike Barcroft wrote:

> [-hackers removed from CC]
> 
> Andrew L. Neporada <andrew@nas.dgap.mipt.ru> writes:
> > I think you should write in ststr.3 that strnstr locates first occurrence
> > of null-terminated string 'little' in ___null-terminated___ string 'big'.
> 
> No, that's inconsistent with existing strn...() functions and totally
> defeats the purpose of my addition.
> 

Check attached test program. It prints "NULL". So either implementation or
man page is wrong.

> To quote from my patch:
> : Add a new libc function, strnstr(3), which allows one to limit the
> : number of characters that are searched.  This is especially useful
> : with file operations and non-NUL terminated strings.
> 
> > P.S. Because str(n)str functions deal with null-terminated strings
> > (i.e. we don't know sizes of strings), it is impossible to write
> > algorithm, that will work faster (in average) than current implementation.
> 
> See above.
> 
> > P.P.S. In the case of binary strings it is possible to implement faster
> > search -- see attachment.
> 
> Yes.

Could you please comment my bstrstr implementation?

> 
> 
> Best regards,
> Mike Barcroft
> 

Andrew.

[-- Attachment #2 --]
#include <string.h>
#include <stdio.h>

/*
 * Find the first occurrence of find in s, where the search is limited to the
 * first slen characters of s.
 */
char *
strnstr(s, find, slen)
	const char *s;
	const char *find;
	size_t slen;
{
	char c, sc;
	size_t len;

	if ((c = *find++) != '\0') {
		len = strlen(find);
		do {
			do {
				if ((sc = *s++) == '\0' || slen-- < 1)
					return (NULL);
			} while (sc != c);
			if (len > slen)
				return (NULL);
		} while (strncmp(s, find, len) != 0);
		s--;
	}
	return ((char *)s);
}

int
main(void)
{
	char	str[10] = {'a', 'b', 'c', '\0', 'a', 'b', 'c', 'd', 'e', 'f'};
	char	*pat = "abcd";
	char	*ptr;

	ptr = strnstr(str, pat, 10);
	
	if (ptr == NULL)
		printf("NULL\n");
	else
		printf("%s\n");
	exit(0);
}

Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.BSF.4.21.0110101958250.51458-200000>