|
-
Jun 14th, 2002, 01:31 PM
#1
Thread Starter
Fanatic Member
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;
}
Alcohol & calculus don't mix.
Never drink & derive.
-
Jun 14th, 2002, 03:34 PM
#2
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;
}
-
Jun 14th, 2002, 09:44 PM
#3
Except remove the GlobalFree() call from the function =).
Z.
-
Jun 15th, 2002, 06:11 AM
#4
Monday Morning Lunatic
Why can't you just return a string and be done with it?
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Jun 15th, 2002, 11:25 AM
#5
Thread Starter
Fanatic Member
Ok, but where's the fun in that?
Alcohol & calculus don't mix.
Never drink & derive.
-
Jun 15th, 2002, 09:19 PM
#6
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|