GP32 Subroutines Returning A String


ConsoleTom

Member
Joined
Dec 4, 2003
Messages
106
Age
47
Location
Germany
Website
Visit site
Here i need SelectFile to return a string.
Is this example ok ? Should i allocate memory in this case ?


...
strcpy(cInputStr,SelectFile("test"));
...

char* SelectFile(char * strStartPath)
{

char * cOutStr;
cOutStr = gm_malloc(256);

strcpy(cOutStr,strStartPath);

gm_free(cOutStr);
return cOutStr;
}
 
do not free your cOutStr variable
but, what's the aim of this function
you can directly write

strcpy(cInputStr,"test");

if you want to free the vriable

char* str
strcpy(cInputStr,SelectFile(str,"test"));
gm_free(str);
...

char* SelectFile(char* s,const char * strStartPath)
{
s = gm_malloc(256);

strcpy(s,strStartPath);
}

or simply

char*c = SlelectFile("test");
strcpy(cInputStr,c);
gm_free( c);
 
Hi !

The function in the example is now a bit nonsensical. It just returns the string that was passed to it.

The aim will be a file-selector. It starts at the path passed to (strStartPath) it and returns a string containing a chosen file (example: gp:\\gpmm\\drumman.fxe).

When i do not free the variable before returning, will it happen automatically ?

Greetings

Tobias
 
When i do not free the variable before returning, will it happen automatically ?
no.
just do it after the function call, but ofcourse you have to save the result in a char*
so, instead of calling your function directly in the strcpy function, just call it before, save the result and then free it
just like this
Code:
char*c = SlelectFile("test");
strcpy(cInputStr,c);
gm_free( c);
but dont free what you are returning... its non-sense
 
Hi !

Thanks so far.

But freeing a variable declared in a sub seems problematic to me because it is a source for errors since it's easy to forget it.

Could this be a solution ?

void SelectFile(char * strStartPath)
{

// do something with the string using pointers
strcpy (&strStartPath,"lalala");
}
 
A better way to do this is pass string space to the function, so the calling code is entirely responsible for any allocation/deallocation of memory used for it.

eg:


char strFilename[256];

SelectFile(strFilename);



void SelectFile(char *strStartPath)
{
strcpy(strStartPath, "blahblahblah");
}
 
Back
Top