Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in C: Why does a stack allocated structure exist outside of the function?

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?

like image 627
Ritwik Bose Avatar asked Feb 28 '10 19:02

Ritwik Bose


People also ask

How is stack allocated?

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.

Why stack memory is used in C?

Stack memory The stack is used to store variables used on the inside of a function (including the main() function).

Are functions stored in stack or heap?

Functions are objects. Therefore, the function's identifier is in the stack, and the function's value is stored in the heap.


2 Answers

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.

like image 144
Gabe Avatar answered Sep 27 '22 15:09

Gabe


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.

like image 36
kennytm Avatar answered Sep 27 '22 17:09

kennytm