https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109306

            Bug ID: 109306
           Summary: The strstr function might do undefined behavior (out
                    of bounds mem access)
           Product: gcc
           Version: 13.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: pmorf at apple dot com
  Target Milestone: ---

Hi,

I think strstr

https://gcc.gnu.org/git/?p=gcc.git;a=blob_plain;f=libiberty/strstr.c;hb=HEAD

may run into undefined behavior by reading the process memory way past the end
of s1.
The implementation will still run memcmp even starting on the last character of
s1, for the full length of s2.
That also means returning null if len(s2) > len(s1) is not enough.

Something along those lines would possibly work :

    char* strstr (const char* s1, const char* s2)
    {
        const size_t s1Len = strlen (s1);
        const size_t s2Len = strlen (s2);

        if (s1Len < s2Len) return (0);

        const char* const endSearchPtr = s1 + s1Len - s2Len;
        while (s1 <= endSearchPtr && *s1)
        {
            if (!memcmp (s1, s2, s2Len))
                return s1;
            ++ s1;
        }
        return (0);
    }

Reply via email to