On Nov 20, 8:13 pm, Joseph M. Newcomer <newco...@flounder.com> wrote:
See below...
On Mon, 19 Nov 2007 20:52:25 -0800 (PST), hari <haricib...@gmail.com> wrote:
Hi all,
I am calling a function that returns a handle, handle is created
by CreateFile API.If I need to close handle by CloseHandle API.How to
close it.
Example:
HANDLE Create();
HANDLE h1,h2;
****
Good methodology in programming says
(a) there are no global variables
(b) never use commas in declaration lists. One variable, one line
****>int main();
{
h1=Create();
****
CloseHandle(h1)
that will work fine>return 0;
}
HANDLE Create()
{
h2 = Createfile() API
//Assume it is success
return h2;
/* I need to close this handle h2 by CloseHandle()API,how can I do
it , because there will be a resource leak*/
****
Why do you think there is a resource leak? You have the handle in the parent, so there is
no leak there, until you fail to free it. Both h1 and h2 are simple numeric variables
whose value represents a kernel object; they are disguised as the HANDLE type so you don't
make coding errors, but they're just pointer-sized values. So you end up in this case
with two copies of the same pointer-sized value. But you shouldn't be assigning h2 at
all, and it should not exist.>}
****
Given the very, very bad technique of using global variables here, you could do
CloseHandle(h1) or CloseHandle(h2). But it would be a Really Bad Idea to have h2 be a
global variable, and h1 be a global variable. One of the first rules of modern
programming is that if you have ever written a global variable, you've probably made a
serious coding error, except in very rare conditions, and I don't see those here.
I would have written this as:
HANDLE Create();
int _tmain(int argc, _TCHAR argv[])
{
HANDLE h1;
h1 = Create();
... do stuff with h1
CloseHandle(h1);
return 0;
}
HANDLE Create()
{
HANDLE h;
h = CreateFile(...);
return h;
}
Note there is no global variable here, because none needs to exist.
joe
*****
Joseph M. Newcomer [MVP]
email: newco...@flounder.com
Web:http://www.flounder.com
MVP Tips:http://www.flounder.com/mvp_tips.htm