Magicloud
Magicloud

Reputation: 857

How do I know it is OK to free the pointer after passed it to a function?

For example, https://developer.gnome.org/gdk3/stable/gdk3-Windows.html#gdk-window-begin-draw-frame, takes a pointer to region as parameter. So how do I know it does not store it somewhere to use later? Or may I free the pointer right after calling the function? Is there any general routine in GTK?

Thanks.

Upvotes: 2

Views: 99

Answers (1)

glglgl
glglgl

Reputation: 91049

Generally, this problem can be solved with the concept of "ownership" of the pointer resp. the associated memory area.

Essentially, the function has to define if it takes ownership of the area (in this case, you pass it to that function and don't have to care about it, but OTOH you necessarily have to allocate it in a way that the function is fine with), or if it just "borrows" the pointer. In this case, it remains yours, and the function just temporarily uses it.

A third alternative is a mixed case: the function borrows ownership, but requires you to keep the memory remains allocated (i. e. usable) until a certain action occurs (e. g. freeing a given resource). In this case, it is your choice where to pick the memory from (heap, stack, static memory etc.), but it is your responsibility to keep it usable long enough.

What the function does should be documented somewhere.

Upvotes: 3

Related Questions