why free() used in malloc?

Discussion in 'C' started by Tango Issac Debian, May 10, 2006.

  1. Tango Issac Debian

    Tango Issac Debian New Member

    Joined:
    May 3, 2006
    Messages:
    31
    Likes Received:
    1
    Trophy Points:
    0
    Hallo

    Experts,

    see the two declarations .....

    i) int i;
    ii)p=(int*)malloc(size of(int));


    Both of this functions used here to allocate the memory .But in case of the malloc ,we use then the free(p),But not for the case of int i,,,,,,,,,,,,,,,,,,,,,,,,

    Why? Please REPLY....................See u again...........

    from
    TANGO
     
  2. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    736
    Likes Received:
    39
    Trophy Points:
    28
    Through malloc you achieve dynamic memory allocation and dynamically allocated object remains allocated until it is deallocated explicitly, either by the programmer or by a garbage collector.

    Static memory allocation refers to the process of allocating memory at compile-time before the associated program is executed.

    So to summarize if you allocate the memory you need to be freeing it up or if compiler allocates it for you, you dont need to be freeing it up.
     
  3. Aztec

    Aztec New Member

    Joined:
    May 9, 2006
    Messages:
    90
    Likes Received:
    0
    Trophy Points:
    0
    First of all

    Code:
    int i;
    
    is not a function its a defination(as well as decleration).Whenever compiler comes across such statement, it automatically allocates memory(amount varies from compiler to compiler) on stack at compile time. There is no function in standard "C" to explicitly delete the statically allocated memory. This memory will automatically be deleted by compiler as the scope of the variable ends. You do not need to worry about it.

    Any memory allocation done by malloc or calloc is done on heap. It becomes the responsibilty of the programmer to make sure that memory should be released after use.

    Don't even think of using free on statically allocated memory. It will most probably be leading to crashing of program.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice