Reputation: 135
I'm trying to understand how the Win32 API handles Pointer ownership.
The concrete example i am looking at right now is the ownership of pointers to strings that i pass to the API and that i get from the API.
Take for example the SetWindowText
function. It takes an LPCSTR
, a pointer to a null terminated widestring.
Another example would be the RegisterClass
function and in conjunction the WNDCLASS
struct.
The RegisterClass
function takes a pointer to a WNDCLASS
struct and the WNDCLASS
struct again contains a LPCSTR
to the class name.
Does the API take ownership of that memory or do i need to handle freeing it?
It seems unlikely to me that it would take ownership but my knowledge of C/C++ conventions isn't good enough to say for certain, and i cant find any documentation about ownership conventions for the API.
Upvotes: 2
Views: 455
Reputation: 2812
Does the API take ownership of that memory or do i need to handle freeing it?
There is no such automatic memory management in Win32 API
. If you allocate some data in your program and give this data to Win32 API
functions, you will have to free
it in your program.
API
in C are usually designed like that, because there is no way for the other layers to determine if the pointers are used somewhere else in the program. If manual memory management is annoying for you, you could search for garbage collectors
which will manage the memory automatically for you, with a small tradeoff regarding performances.
Upvotes: 1
Reputation: 8171
The general answer is: Read the documentation for the function in question. If it doesn't say anything about taking ownership, then it's a good bet that it doesn't take ownership and you need to deal with the memory.
Although it's been a while since I did much significant work at the level of the Windows API, I recall occasionally coming across functions that documented they required memory to be allocated via a particular method in first place - because that's the only way to know how to properly deallocate it.
And that leads to the second way to reason about this. Imagine you were the implementer of the function. If you were just given a raw pointer with no other information about it, could you know how the deallocate the memory it points to? Was that memory allocated with new
? malloc
? some other API call? or maybe it's on the stack? C / C++ / the level of the Windows API doesn't have any facility to determine how memory was allocated from just having a pointer alone. So most functions are just not going to deal with that hassle if they don't need to. And the few that have a good reason will have to follow the route of documenting their requirements.
Upvotes: 5