Dynamic memory allocation.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gsi
    New Member
    • Jul 2007
    • 51

    Dynamic memory allocation.

    HI,
    I am not sure whether this code is legal... Its works fine, but I am afraid that this is not a valid thing to be done. I am freeing the returned dynamically allocated memory in the main function. In the following code below, Is the freeing of memory in either of the functions is the same, or else there is a memory leak?.

    [code=c]

    char * foo(void){
    char *a = (char*)malloc(s izeof(char)*2);
    return a;
    }


    int main(){

    char *p = foo();
    //do some thing with 'p' here....
    free p;
    return 0;
    }

    [/code]


    Thanks,
    Gsi.
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    Seems fine to me.

    Comment

    • gsi
      New Member
      • Jul 2007
      • 51

      #3
      Hi,
      Thanks for the quick reply. Since I am freeing a copy of pointer, but eventually it is the same in value context, is it the same as freeing the original pointer ?.

      Thanks in advance,
      Gsi.

      Comment

      • ilikepython
        Recognized Expert Contributor
        • Feb 2007
        • 844

        #4
        Originally posted by gsi
        Hi,
        Thanks for the quick reply. Since I am freeing a copy of pointer, but eventually it is the same in value context, is it the same as freeing the original pointer ?.

        Thanks in advance,
        Gsi.
        I believe so, yes. When you free a pointer you are freeing the memory allocated at the location in which the pointer points. So you are freeing the same memory you allocated in the function because you preserved the address.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Be aware that after you free a pointer the memory it pointed at is up for grabs. Should there be another pointer in the program pointing at that memory location, the program will crash if you attempt to free the other pointer.

          You can't free unless you are certain no copies of the address in the pointer are tucked away in the program somewhere.

          Comment

          • gsi
            New Member
            • Jul 2007
            • 51

            #6
            Hi,


            [QUOTE : Weaknessforcats]You can't free unless you are certain no copies of the address in the pointer are tucked away in the program somewhere.[/QUOTE]

            [QUOTE ilikepython]
            When you free a pointer you are freeing the memory allocated at the location in which the pointer points. So you are freeing the same memory you allocated in the function because you preserved the address.[/QUOTE]


            Thanks guys, for clearing it up.


            Thanks,
            gsi.

            Comment

            Working...