C++ interop issue due to non-null pointers
Jonathan Wakely
jwakely.gcc@gmail.com
Thu Jun 12 10:04:00 GMT 2014
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.
More information about the Gcc
mailing list