randy newfield
randy newfield

Reputation: 1221

Freeing pointers

This is just a general question, but for example on windows, if i create a pointer to a hostent struct to use with gethostbyname() do i have to dealocate memory of that pointer or is it handled for me. I am under the assumption that since I did not specifically call malloc on it that it is not my job. Can anyone clarify this for me?

Thank you

Upvotes: 3

Views: 281

Answers (2)

Samuel Edwin Ward
Samuel Edwin Ward

Reputation: 6675

In the case of gethostbyname you do not have to worry about freeing the storage.

In general, a function returning a pointer should document the caller's responsibilities regarding the pointer. You might need to free it, pass it to another function, or as in this case not have to do anything.

With strdup, as a counterexample, you should call free.

Upvotes: 0

75inchpianist
75inchpianist

Reputation: 4102

according to msdn

The memory for the hostent structure returned by the gethostbyaddr and gethostbyname functions is allocated internally by the Winsock DLL from thread local storage. Only a single hostent structure is allocated and used, no matter how many times the gethostbyaddr or gethostbyname functions are called on the thread. The returned hostent structure must be copied to an application buffer if additional calls are to be made to the gethostbyaddr or gethostbyname functions on the same thread. Otherwise, the return value will be overwritten by subsequent gethostbyaddr or gethostbyname calls on the same thread. The internal memory allocated for the returned hostent structure is released by the Winsock DLL when the thread exits.

So the only time you need to free it is if you are copying its contents to memory you allocated

Upvotes: 5

Related Questions