my function:
struct hostent * gethost(char * hostname){
if(/*some condition under which I want
to change the mode of my program to not take a host*/){
return null
}
else{
struct hostent * host = gethostbyname(hostname);
return host;
}
}
in main:
struct hostent * host = gethost(argv[2]);
(ignore any minor errors in the code, I'm spewing from memory)
this works fine. and Valgrind doesn't tell me I'm losing memory, despite the fact I'm not freeing.
Why? I thought stuff allocated on the stack disappears with the function call returning? or is it because I return the pointer? is this dangerous in any way?
Stack memory is allocated in a contiguous block whereas Heap memory is allocated in any random order. Stack doesn't require to de-allocate variables whereas in Heap de-allocation is needed.
Stack memory The stack is used to store variables used on the inside of a function (including the main() function).
Functions are objects. Therefore, the function's identifier is in the stack, and the function's value is stored in the heap.
host
is not allocated on the stack, only a pointer to it is on the stack. The pointer gets copied when the function returns, so there is nothing wrong with the code.
Note that gethostbyname
does not actually dynamically allocate memory. It always returns a pointer to the same statically allocated block of memory, which is why valgrind doesn't report a leak. Be careful, though, because that means you have to copy the hostent
returned by your function if you want to save the value for later because further calls to gethost
will overwrite it.
It's fine and does leak because the returned pointer doesn't point to data on stack or heap, but some static variable.
http://linux.die.net/man/3/gethostbyname:
The functions gethostbyname() and gethostbyaddr() may return pointers to static data, which may be overwritten by later calls. Copying the struct hostent does not suffice, since it contains pointers; a deep copy is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With