octave-bug-tracker
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Octave-bug-tracker] [bug #54373] strncmp does not compute result accura


From: Rik
Subject: [Octave-bug-tracker] [bug #54373] strncmp does not compute result accurately when N exceeds string length
Date: Wed, 25 Jul 2018 13:02:02 -0400 (EDT)
User-agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0

Follow-up Comment #3, bug #54373 (project octave):

Well, its not quite as simple as I thought.  I took out the checks on numel
and the routine can still fail.


octave:1> strncmp ('abc', 'abc', 100)
ans = 0
octave:2> strncmp ('abc', 'abc', 3)
ans = 1
octave:3> strncmp ('abc', 'abc', 4)
ans = 1
octave:4> strncmp ('abc', 'abc', 5)
ans = 1


The problem is that str_data_cmp just accepts whatever value of 'n' is used
and compares memory locations.  That means it will walk beyond the real data
unless n is correctly sized


str_data_cmp (const typename T::value_type *a, const typename T::value_type
*b,
              const typename T::size_type n)
{
  for (typename T::size_type i = 0; i < n; ++i)
    if (a[i] != b[i])
      return false;
  return true;
}


So, here's a different version


template<typename T>
bool
octave::string::strncmp (const T& str_a, const T& str_b,
                         const typename T::size_type n)
{
  typename T::size_type neff;
  auto len_a = numel (str_a);
  auto len_b = numel (str_b);
  neff = std::min (std::max (len_a, len_b), n); 

  return (len_a >= neff && len_b >= neff
          && str_data_cmp<T> (str_a.data (), str_b.data (), neff));
}


This adds a call to std::min and std::max which shouldn't be particularly
performance intensive.



    _______________________________________________________

Reply to this item at:

  <http://savannah.gnu.org/bugs/?54373>

_______________________________________________
  Message sent via Savannah
  https://savannah.gnu.org/




reply via email to

[Prev in Thread] Current Thread [Next in Thread]