pijush has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I am facing a problem to delete memory which is allocated using Nexz function. Here is my sample programme, in my sample programme I want to concatenate two strings and show the result.
First .h file (StringTest.h)
===========================

#include <stdio.h> #include <stdlib.h> #include <string.h> char* StringAdd (char* x, char* y); void FreeMemory (void* z);
.c File (StringTest.c)
======================
#include "StringTest.h" char* StringAdd (char* x, char* y) { char* ReturnString; int Length = strlen(x) + strlen(y); ReturnString = (char*) malloc (Length*sizeof(char)); strcpy (ReturnString, x); strcat (ReturnString, y); return ReturnString; } void FreeMemory (void* z) { void* current = NULL; current = z; free (current); current = NULL; if (NULL == current ) { printf ("Memory deallocated\n"); } }
.xs file (MyStringTest.xs)
===========================
#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #define XARG 123 #include "StringTest.h" MODULE = MyStringTest PACKAGE = MyStringTest char* TestStringAdd (a,b) char* a char* b CODE: char* c; char* d; int length; c = StringAdd(a, b); length = strlen(c); Newz (XARG, d, length, char*); strcpy (d, (const char*)c); // deallocate Memory FreeMemory (c); printf ("Name::%s\n", d); printf ("Length::%d\n", length); RETVAL = d; OUTPUT: RETVAL
Test file (test.pl)
========================
use Test; BEGIN { plan tests => 1 }; use MyStringTest; print MyStringTest::TestStringAdd(Pijush, Koley), "\n"; ok(1); # If we made it this far, we're ok.
The code is working fine. But there is memory leakage problem in the code. I am doing a Newz, but no corresponding Safefree is there. I want to avoid the memory leakage problem. I know if I rewrite the programme in OO model, then in DESTROY method I can call Safefree function. Can you please suggest me any other method so that I do not need to rewrite the complete function?
Thanks in advance.
-Pijush

Replies are listed 'Best First'.
Re: Help needed for Perl XS code
by gellyfish (Monsignor) on Jan 14, 2005 at 14:42 UTC

    WOuld it be possible rather than allocating memory for the char * return that you could instead return an SV *? You could do away with the the Newz() and strcpy and end up with something like (untested):

    SV * TestStringAdd (a,b) char* a char* b CODE: char* c; SV* d; int length; c = StringAdd(a, b); length = strlen(c); d = newSVpv(c,length); // deallocate Memory FreeMemory (c); printf ("Name::%s\n", d); printf ("Length::%d\n", length); RETVAL = d; OUTPUT: RETVAL
    This will at the least save dicking around with the allocations and let perl deal with it.

    /J\

      Thanks. It is working perfectly fine.