Hi,
Windows 2000, perl5.6.1, Inline-0.44.
The simple test script below contains 2 similar functions - test2(), which
works fine - and test1(), which attempts to perform the same task as
test(2), but does so by calling c_push_si().
test1() is prone to error and crashing (details below).
----------------------------------------------------
use strict;
use warnings;
use Inline C => <<'END';
void c_push_si(int * array, int * ptr, int el){
++ *ptr;
Renew(array, *ptr, int);
array[*ptr - 1] = el;
}
void test1(int its) {
int * arr, len = 0, * lenptr, i;
if(its < 1) croak("Get with it");
lenptr = &len;
Newz(2, arr, 1, int);
if(arr == NULL) croak("Failed to allocate memory for array in test
function");
for(i = 0; i < its; ++i)
c_push_si(arr, lenptr, i * 7);
for(i = 0; i < len; ++i) printf("%d ", arr[i]);
Safefree(arr);
}
void test2(int its) {
int * arr, len = 0, i;
if(its < 1) croak("Get with it");
Newz(2, arr, 1, int);
if(arr == NULL) croak("Failed to allocate memory for array in test
function");
for(i = 0; i < its; ++i) {
++len;
Renew(arr, len, int);
arr[len - 1] = i * 7;
}
for(i = 0; i < len; ++i) printf("%d ", arr[i]);
Safefree(arr);
}
END
my $its = 3;
test1($its);
print "\n";
$its = 13;
test2($its);
----------------------------------------------------------
If $its is less than 3, everything works ok. If $its is greater than 3,
test1() crashes and windows shuts the program down.
If $its equals 3, things run ok, but the third value printed by test1() is
garbage.
Is this problem due to the memory block being moved ?
All I wanted was to have c_push_si() emulate perl's push() function, so that
I could just call *it* from within my inline-C functions whenever I want to
push a value onto an int array. Is there a smarter approach to achieving
this emulation ?
Or do I have to code up the Renew()-and-assign rigmarole every time I want
to push a value onto an array ?
Also on the subject of Renew() - should I be checking that the reallocation
was successful, and if so, how do I do that ?
Cheers,
Rob