-
Returning a pointer
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?
Code:
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;
}
-
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
Code:
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;
}
-
Except remove the GlobalFree() call from the function =).
Z.
-
Why can't you just return a string and be done with it? :)
-
Ok, but where's the fun in that? ;)
-
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.