octave-maintainers
[Top][All Lists]
Advanced

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

Re: C++ string::find functions and size_t


From: John W. Eaton
Subject: Re: C++ string::find functions and size_t
Date: Fri, 27 Feb 2015 18:56:05 -0500
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Icedove/31.2.0

On 02/27/2015 06:37 PM, Andreas Weber wrote:
Am 27.02.2015 um 18:47 schrieb rik:
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 --

I think the idea here was to check if the first char in file is "|" and
omit the check (because we are building a pipe) for an existent
directory in the else path.

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 --

Please correct me if I'm wrong but shouldn't this then be

-- Code --
size_t pos = file.find_first_not_of ("|");
if (pos != std::string::npos && pos > 0)
-- End Code --

Yes, I think that's correct. I also thought maybe it would be clearer to write if (file.length () > 0 && file[0] == '|'), then just extract get file.substr (1) as the command. Shouldn't that work? It looks simpler to me.

jwe





reply via email to

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