This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: C++ interop issue due to non-null pointers
- From: Jonathan Wakely <jwakely dot gcc at gmail dot com>
- To: Florian Weimer <fweimer at redhat dot com>
- Cc: GCC <gcc at gcc dot gnu dot org>
- Date: Thu, 12 Jun 2014 11:04:26 +0100
- Subject: Re: C++ interop issue due to non-null pointers
- Authentication-results: sourceware.org; auth=none
- References: <53997584 dot 8080706 at redhat dot com>
On 12 June 2014 10:40, Florian Weimer wrote:
> In GCC 4.9, we have optimizations that make use of non-null annotations, at
> least for removing null pointer checks. Some libc functions are annotated
> with it, such as qsort, memcpy, memset, memcmp.
Yep, as described at https://gcc.gnu.org/gcc-4.9/porting_to.html
> On the other hand, it is unspecified if the data() member of std::vector
> returns null pointer if empty() returns true.
>
> As a result, code like this is invalid if the functions are ever called with
> empty vectors:
>
> void clear(std::vector<char> &vec)
> {
> memset(vec.data(), '\0', vec.size());
> }
>
> int comparefn(void *, void *);
>
> void sort(std::vector<T> &vec)
> {
> qsort(vec.data(), vec.size(), sizeof(T), comparefn);
> }
>
> I think this is quite surprising.
I don't see why it's much different to passing a pointer that might be
null. You need to check.
> What can we do about it?
How common is it to use std::vector with qsort, rather than
std::sort(vec.begin(), vec.end()), which does the right thing?
We could make vector::data() guarantee a non-null pointer with
_FORTIFY_SOURCE, but I'd rather not do so in "unfortified" code. Some
users would object to the extra check needed.