[libvirt] [PATCH 2/2] Adapt to new VIR_STRNDUP behavior

Eric Blake eblake at redhat.com
Fri May 24 13:37:24 UTC 2013


On 05/24/2013 06:57 AM, Michal Privoznik wrote:
> On 24.05.2013 11:53, Michal Privoznik wrote:
>> With previous patch, we accept negative value as length of string to
>> duplicate. So there is no need to pass strlen(src) in case we want to do
>> duplicate the whole string.
>> ---

>> -        if (VIR_STRNDUP(arg, curr, next ? next - curr : strlen(curr)) < 0)
>> +        if (VIR_STRNDUP(arg, curr, next ? next - curr : -1) < 0)
> 
> Or we can even go with 'VIR_STRNDUP(arg, curr, next - curr) < 0' but
> that's not so easy to read. The rationale behind is: I intentionally
> made VIR_STRNDUP to accept *any* negative value, not just -1. Because if
> strrchr(cur, '\n') just a few lines above fails, next is just NULL.
> Deducting from NULL will get a negative value. Which will make
> VIR_STRNDUP duplicate the while string. But I worry that it would be an
> ugly code, wouldn't it?

It would be undefined behavior according to the C standard.  Pointer
subtraction is only well-defined within the bounds of a single object;
your object (in C terminology) starts at 'curr' and ends at the NUL byte
that terminates 'curr'.  NULL falls outside that bounds.  'next - curr'
is not guaranteed to be negative, since C says the behavior is
undefined.  Stick with the long form.

-- 
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 621 bytes
Desc: OpenPGP digital signature
URL: <http://listman.redhat.com/archives/libvir-list/attachments/20130524/ebc831fd/attachment-0001.sig>


More information about the libvir-list mailing list