Use STRLEN not int for SvPV

Obscure bugs occur with the following type of code:

 unsigned int len;
 c = SvPV (sv, len);

The bugs occur typically on a 64 bit system. They happen because unsigned int may be a 32 bit integer, but the second argument to SvPV should be STRLEN, which is unsigned long int. Giving a pointer to a 32-bit integer where it expects a 64-bit integer causes some very odd bugs, and may even crash the interpreter. So, one has to always do like this:

 STRLEN len;
 c = SvPV (sv, len);

and never use anything which is not STRLEN type.

I have a collection of more weird and wonderful XS bugs, found through CPAN testers, here:

https://www.lemoda.net/perl/perl-xs-cpan-testers/index.html

Despite having known about this for years, I just found another instance in my own module, thanks to the warning messages from clang, in Text::Fuzzy:

https://metacpan.org/source/BKB/Text-Fuzzy-0.26/Fuzzy.xs#L51

I've just now updated it:

https://metacpan.org/source/BKB/Text-Fuzzy-0.27/Fuzzy.xs#L51

Perhaps it would be worth making some kind of automated checker to go through XS code and make sure the second argument to strlen is always STRLEN.

Leave a comment

About Ben Bullock

user-pic Perl user since about 2006, I have also released some CPAN modules.