PDA

Click to See Complete Forum and Search --> : Returning a pointer


Wynd
Jun 14th, 2002, 01:31 PM
Ok, here is my problem: I am trying to write a function to get the text of an edit box (not the dialog kind). I want to return a char*, but if I free the memory first, there is nothing to return. If I return first, the memory doesn't get freed. What can I do?


char* getText()
{
int len = GetWindowTextLength(m_hParent);
char* buf = (char*)GlobalAlloc(GPTR, len + 1);

GetWindowText(m_hParent, buf, len + 1);

GlobalFree((HANDLE)buf);

return buf;
}

jim mcnamara
Jun 14th, 2002, 03:34 PM
In general, when you call a routine, it cannot return pointers it creates to memory it allocates.

Allocate memory either in main() or in the calling function.

Some programmers create a global buffer for just such use

static char globalbuf[4096];

int main(void){

..........// stuff

}

char* getText()
{
int len = GetWindowTextLength(m_hParent);
char* buf = globalbuf;

GetWindowText(m_hParent, buf, len + 1);

GlobalFree((HANDLE)buf);

return buf;
}

Zaei
Jun 14th, 2002, 09:44 PM
Except remove the GlobalFree() call from the function =).

Z.

parksie
Jun 15th, 2002, 06:11 AM
Why can't you just return a string and be done with it? :)

Wynd
Jun 15th, 2002, 11:25 AM
Ok, but where's the fun in that? ;)

jim mcnamara
Jun 15th, 2002, 09:19 PM
Look at C. strcpy(), strstr(), strchr()
ALL return a pointer to one of the arguments - they don't create a pointer out of thin air. Which is what you're trying to do.