3

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

randy newfield
  • 1,221
  • 3
  • 25
  • 38
  • 1
    Please show code; I do not understand what you mean by "create a pointer to a hostent struct". – zwol Feb 20 '13 at 19:41

2 Answers2

5

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

75inchpianist
  • 4,112
  • 1
  • 21
  • 39
0

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.

Samuel Edwin Ward
  • 6,526
  • 3
  • 34
  • 62