|
From: | Konstantinos Poulios |
Subject: | Re: C++ string::find functions and size_t |
Date: | Sun, 1 Mar 2015 20:10:16 +0100 |
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
[Prev in Thread] | Current Thread | [Next in Thread] |