Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Offset from a memory address

Tags:

c++

I was reading some code and I came across this example. What I don't understand is why the author uses an offset of 1 from both variables on the last line. At first glance I would assume this is illegal because it is referring to a possibly uninitialized memory area (and it could cause a segmentation fault). My head keeps telling me undefined behavior but is this really so?

static bool lt(wchar_t a, wchar_t b)
{
    const std::collate<wchar_t>& coll =
        std::use_facet< std::collate<wchar_t> >(std::locale());
    return coll.compare(&a, &a+1, &b, &b+1) < 0;
}

The last line is the one in question. Why is it necessary that he's doing this, is it legal, and when should it be done?

like image 527
David G Avatar asked Feb 17 '26 05:02

David G


1 Answers

It appears that the author just wanted to compare two characters using the current global locale.

Since std::collate<T>::compare uses [low, high) for the two ranges, adding 1 to the address of the parameters will simply cause the comparison to stop after only a is compared to b. There should be no invalid memory accesses.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!