pijush has asked for the wisdom of the Perl Monks concerning the following question:
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)
===========================
.c File (StringTest.c)#include <stdio.h> #include <stdlib.h> #include <string.h> char* StringAdd (char* x, char* y); void FreeMemory (void* z);
.xs file (MyStringTest.xs)#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"); } }
Test file (test.pl)#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
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?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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Help needed for Perl XS code
by gellyfish (Monsignor) on Jan 14, 2005 at 14:42 UTC | |
by pijush (Scribe) on Jan 14, 2005 at 16:17 UTC |