Reputation: 63767
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
Should not be freed because
What should be the approach?
Upvotes: 2
Views: 1953
Reputation: 2170
Yes, you should always free heap-allocated memory when you're done using it and know that it is safe to do so. The documentation you link to even states:
For functions that allocate memory as if by malloc(), the application should release such memory when it is no longer required by a call to free(). For wcsdup(), this is the return value.
If you are concerned about the free being potentially confusing, leave a comment explaining it. To be honest, though, that seems superfluous; it's pretty obvious when a pointer is explicitly freed that it's "owned" by the code freeing it, and anyone who does become confused can easily look up the wcsdup
documentation.
Also, you should really never have memory leaks in your program. In practice some programs do have memory leaks, but that doesn't mean it's okay for them to exist. Also note that just because you have a block of memory allocated for the entire lifespan of the program, it is not leaked memory if you are still using it for that entire duration.
Upvotes: 2
Reputation: 4287
From your own link:
For functions that allocate memory as if by malloc(), the application should release such memory when it is no longer required by a call to free().
From MSDN:
The _strdup function calls malloc to allocate storage space for a copy of strSource and then copies strSource to the allocated space.
and strdup is deprecated as from MSVC 2005 and calling it calls _strdup so it is using malloc
Upvotes: 0
Reputation: 91915
From MSDN:
it is good practice always to release this memory by calling the free routine on the pointer returned
From the page you linked:
The returned pointer can be passed to free()
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:
We always live with some memory leaks through out the program lifetime
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?
Upvotes: 12