A simple XS function in PDL, firstvals_nophys, was giving "panic: attempt to copy freed scalar", but only if called on a complex-valued ndarray. The aim of this post is to appear when a despairing XS programmer googles that message, and give them another thing to check. When constructing a test to capture this, another message that appeared was "Bizarre copy of ARRAY". This is the old text of the function:
void
firstvals_nophys(x)
pdl *x
PPCODE:
if (!(x->state & PDL_ALLOCATED)) barf("firstvals_nophys called on
+non-ALLOCATED %p", x);
PDL_Indx i, maxvals = PDLMIN(10, x->nvals);
EXTEND(SP, maxvals);
for(i=0; i<maxvals; i++) {
PDL_Anyval anyval = pdl_get_offs(x, i);
if (anyval.type < 0) barf("Error getting value, type=%d", anyval
+.type);
SV *sv = sv_newmortal();
ANYVAL_TO_SV(sv, anyval);
PUSHs(sv);
}
The problem was that the ANYVAL_TO_SV macro was, only for complex-valued data, calling a Perl function to create a Math::Complex object (well, a subclass thereof because the overloads were wrong). That obviously uses the top of the stack, including writing values into it, and reading values out of it, including mortal ones that then got freed because they were done with. Therefore, the function was returning with some garbage on the stack, but the last value was correct.
The solution was simply to do a PUTBACK after the PUSH, which moves the top of the stack above data we care about. The new text of the function with that:
void
firstvals_nophys(x)
pdl *x
PPCODE:
if (!(x->state & PDL_ALLOCATED)) barf("firstvals_nophys called on
+non-ALLOCATED %p", x);
PDL_Indx i, maxvals = PDLMIN(10, x->nvals);
EXTEND(SP, maxvals);
for(i=0; i<maxvals; i++) {
PDL_Anyval anyval = pdl_get_offs(x, i);
if (anyval.type < 0) barf("Error getting value, type=%d", anyval
+.type);
SV *sv = sv_newmortal();
ANYVAL_TO_SV(sv, anyval);
PUSHs(sv);
PUTBACK;
}
The commit that fixed this is at https://github.com/PDLPorters/pdl/commit/68389413537c6ea7ed85f121a580b3b008ba82a6. The docs on how to call a Perl function from C are at https://perldoc.perl.org/perlcall, with a full explanation of PUSHMARK, PUSH*, PUTBACK, and (after the call) SPAGAIN, and maybe POP* and maybe then PUTBACK.
|