[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
C++ string::find functions and size_t
From: |
rik |
Subject: |
C++ string::find functions and size_t |
Date: |
Fri, 27 Feb 2015 09:47:17 -0800 |
2/27/15
Dan Sebald found a subtle bug in the use of the C++ string find functions
that was leading to segfaults.
-- Code --
size_t pos = file.find_first_not_of ("|");
if (pos > 0)
file = file.substr (pos);
else
-- End Code --
The issue is that the size_t is an unsigned quantity and the find functions
do not return -1 on failure as do regular C functions. Instead they return
std::string::npos (a very large number) when they fail to find the search term.
This was easily corrected to
-- Code --
size_t pos = file.find_first_not_of ("|");
if (pos != std::string::npos)
file = file.substr (pos);
else
-- End Code --
This made me a bit paranoid so I grep'ed through the code and found three
other instances where Octave was using incorrect comparisons or arithmetic
on size_t values returned from find functions. See cset
(http://hg.savannah.gnu.org/hgweb/octave/rev/ed5ee3f610db). At this point,
the test for __osmesa_print__ fails, which is probably good and probably
related to the segfault that has been reported with this test
(https://savannah.gnu.org/bugs/?44360).
Final question on this topic. According to the C++ reference, the find
functions actually return an object of std::string::size_type. Normally,
maybe even definitionally, this is the same as std::size_t. Octave code,
however, assumes that the bare size_t is the same as std::size_t. Should
we care about this? The gl2ps-render.cc code, that maybe we got from
somewhere else originally, does use std::size_t.
--Rik
- C++ string::find functions and size_t,
rik <=