Functions like wcsdup, implicitly calls malloc to allocate memory for the destination buffer. I was wondering as the memory allocation is not very explicit, so does it seems logical to explicitly free the storage?
This is more like a design dilemma and the reasons for and against are as follows
Should be freed because
- Not freeing it would cause Memory Leak.
- It is well documented that wcsdup/_wcsdup calls malloc to allocate memory even when its called from a C++ Program.
Should not be freed because
- Memory accumulated by wcsdup would eventually be freed when program exits. We always live with some memory leaks through out the program lifetime(Unless we are heavily calling wcsdup for large buffer size).
- It can be confusing as free was not preceded by an explicit malloc.
- As its not part of the standard but posix compliant, Microsoft implementation may not use malloc for allocating destination buffer.
What should be the approach?
From MSDN:
From the page you linked:
It seems fairly explicit: if you care about memory leaks, then you should free the memory by using
free.To be honest, I’m concerned about the cavalier attitude hinted at with this:
There are very rarely good reasons to leak memory. Even if the code you write today is a one-off, and it’s not a long-lived process, can you be sure that someone’s not going to copy-and-paste it into some other program?