I am looking for help deallocating memory I reserved in C subroutines in my
Perl module.  First a little background--I am generating images (plotting a
boundary, interpolating a data field, running a smoothing algorithm, etc.).
Sometimes, they are pretty large (several thousand pixels square), so I
needed some sort of memory management to handle them, so I used Inline C.

Say I have a subroutine in my library like this:

sub make_boundary_map {
    my $image = create_image($MAX_SIZE);
    draw_polygon($image,$size_x,$size_y,@points);
    $image_file = open_file("image.tiff");
    write_image($image_file,$image,$size_x,$size_y);
    destroy_image($image);
 }

and my Inline C section contains those functions.

////////////////////////////////////////////////////

char * create_image(int size) {
    char * image = new char[size];
    memset(image,0xFF,size);
    return image;
 }

void destroy_image(char * image) {
    delete [] image;
 }

(assume there are draw_polygon(), open_file(), and write_image() subroutines
as well, and they work fine)

////////////////////////////////////////////////////

How can I rewrite these create/destroy functions such that Perl will
actually reclaim the memory I free?  I have tried using free(), SafeFree(),
the Perl macro New() to create the image, and various other methods.  If
they are in the same subroutine, it works fine:


void test_image(int size) {
    char * image;
    New(123,image,size,char);
    memset(image,CLEAR,size);
    Safefree( (void *) image);
 }

I can run this repeatedly and it works fine

foreach (1..100) {
    test_image_part(5000000);
 }

HOWEVER, if I split it into two functions:

char * test_image_part_1(int size) {
    char * image;
    New(123,image,size,char);
    memset(image,CLEAR,size);
    return image;
 }

void test_image_part_2(char * image) {
    Safefree( (void *) image);
 }

and call them one imediately after the other

foreach (1..100) {
    $image = test_image_part_1(5000000);
    test_image_part_2($image);
 }

it crashes, usually with a seg fault.  There should really be no difference
between the two, but apparently there is.  Anyone out there use Inline to
dynamically create memory space, use it for a while, then free it later with
another function?  An explanation would be good, but an example would be
best. ^_^

Thanks for any help anyone can provide.

--
Dave



Reply via email to