OT: CS education gone wrong (Was: Re: TDD is BS?)
Walter Bright
newshound2 at digitalmars.com
Sat Jun 22 10:42:27 PDT 2013
On 6/22/2013 4:01 AM, Andrej Mitrovic wrote:
> On 6/22/13, Walter Bright <newshound2 at digitalmars.com> wrote:
>> Can I play, too? Mine from the Digital Mars C library. Haven't looked at it
>>
>> #if 0 /* Smaller but slower under many circumstances. */
>> char *strstr(const char *s1,const char *s2)
>> { size_t len2;
>> size_t len1;
>> char c2 = *s2;
>>
>> len1 = strlen(s1);
>> len2 = strlen(s2);
>> if (!len2)
>> return (char *) s1;
>> while (len2 <= len1)
>> {
>> if (c2 == *s1)
>> if (memcmp(s2,s1,len2) == 0)
>> return (char *) s1;
>> s1++;
>> len1--;
>> }
>> return NULL;
>> }
>
> Some things i've noticed about this implementation:
It's wrapped in #if 0 ... #endif ? :-)
> - c2 is assigned by pointer dereference, but then strlen is called on
> s2 and you may get an early exit, meaning c2 was not needed at this
> point. I'd move c2 below the strlen call.
Yup.
> - The memcp doesn't have to compare len2 amount of chars if you've
> already compared the first character, it can call memcmp(s2+1, s1+1,
> len2-1). Although I'm not sure whether it's faster to do it this way
> (maybe it is, if those variables are actually registers..).
Yup.
> And notes about both implementations:
>
> - You're casting a const char * to a char * in the return, you should
> instead provide an overload of strstr taking char* and returning
> char*.
The function bodies would be identical - why have two of them?
> - You seem to have missed the most basic and most important check. You
> didn't attempt to compare the memory address of both pointers against
> each other before doing any other work. If they both point to the same
> memory, the strings are guaranteed to be equal.
Most important? I've never even run across this case.
More information about the Digitalmars-d
mailing list