开发者

When do I need to deallocate memory?

I am using this code inside a class to make a webbrowser control visit a website:

void myClass::visitWeb(const char *url)
{
    WCHAR buffer[MAX_LEN];
    ZeroMemory(buffer, sizeof(buffer));
    MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, url, strlen(url), buffer, sizeof(buffer)-1);

    VARIANT vURL;
    vURL.vt = VT_BSTR;
    vURL.bstrVal = SysAllocString(buffer);

    // webbrowser navigate code...

    VariantClear(&vURL);
}

I call visitWeb from another void function that gets called on the 开发者_开发技巧handlemessage() for the app. Do I need to do some memory deallocation here?, I see vURL is being deallocated by VariantClear but should I deallocate memory for buffer? I've been told that in another bool I have in the same app I shouldn't deallocate anything because everything clear out when the bool return true/false, but what happens on this void?


I think you have some fundamental problems with your understanding of memory management. In this case, no, you don't need to explicitly free any memory. You didn't ever call new, so you don't need to call delete. buffer exists only on the stack, and will vanish when this method returns.


If I might, I'd suggest doing this a bit differently -- I'd start by creating a small class:

class bstr { 
    VARIANT content;
public:
    bstr(char const *url) { 
        WCHAR buffer[MAX_LEN] = {0};
        MultiByteToWideChar(CP_ACP, 
                            MB_ERR_INVALID_CHARS, 
                            url, 
                            strlen(url), 
                            buffer, 
                            sizeof(buffer)/sizeof(buffer[0])-1);
        content.V_T = VT_BSTR;
        content.bstrVal = SysAllocString(buffer);        
    }

    operator VARIANT const &() { return content; }

    ~bstr() { VariantClear(&content); }
};

Then your code would change to something like:

void myClass::visitWeb(const char *url) {
    your_control.Navigate(bstr(url));
}

and all the allocation and freeing gets handled automatically from there.

Even if you don't do use a class like this, note the change to the call to MultiByteToWideChar. The last parameter is supposed to be the number of WCHAR elements in the buffer, not the number of chars. As it is, you've set up a buffer overrun...


I don't see any news, so I wouldn't expect any deletes.

I guess I'd look at the description of SysAllocString() to see if it allocates any memory that you need to get rid of yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜