how to release memory?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mynews

    how to release memory?


    I use free() function to release memory,
    But the memory usage is still increasing.

    cygwin

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    struct queue{
    char data[1024];
    struct queue *next;
    };
    struct queue *myqueue[1024];
    struct queue *pre_item[1024];
    struct queue *first_item[1024];

    void enqueue(int sockfd,char *var){
    myqueue[sockfd]=(struct queue *) malloc(sizeof (struct queue));
    strcpy((char *)&myqueue[sockfd]->data,var);
    myqueue[sockfd]->next=NULL;
    if (pre_item[sockfd]!=NULL){
    pre_item[sockfd]->next=myqueue[sockfd];
    }else{
    first_item[sockfd]=myqueue[sockfd];
    }
    pre_item[sockfd]=myqueue[sockfd];
    }

    char *dequeue(int sockfd){
    char r[1024];
    struct queue *temp;
    temp=first_item[sockfd];
    strcpy(r,temp->data);
    first_item[sockfd]=first_item[sockfd]->next;
    temp=NULL;
    free(temp);
    return r;
    }


  • Mike Wahler

    #2
    Re: how to release memory?


    "mynews" <noreplay@gmail .comwrote in message
    news:g3v1tu$jt$ 1@netnews.hinet .net...
    >
    I use free() function to release memory,
    But the memory usage is still increasing.
    What did you do to determine that?

    Note that many operating systems will keep
    free'd memory in reserve for an application
    until it exits.

    How exactly this is done depends upon your
    operating system, implementation, and possibly
    other factors.

    I didn't look closely at your code, so I can't
    say if it actually leaks or not.

    If you want to test for 'real' memory leaks,
    I suggest a tool made for it, e.g. valgrind.

    -Mike



    Comment

    • rahul

      #3
      Re: how to release memory?

      On Jun 26, 8:20 am, "mynews" <norep...@gmail .comwrote:
      I use free() function to release memory,
      But the memory usage is still increasing.
      >
      temp=NULL;
      free(temp);
      Since when are you allowed to call free(NULL)?
      May be what you want is :
      free(temp);
      temp = NULL;

      I have not seen your code carefully but the approach seems to be
      flawed. You are maintaining 3 array of pointers, each 1024 elements,
      to implement a simple queue. Further, you are freeing only elements in
      first_item (well, as of now, not even that). What about the elements
      of per_item? Your logic is not clear to me. Perhaps you should re-
      consider your data structures and algorithms.

      Comment

      • Richard Heathfield

        #4
        Re: how to release memory?

        rahul said:
        On Jun 26, 8:20 am, "mynews" <norep...@gmail .comwrote:
        >I use free() function to release memory,
        >But the memory usage is still increasing.
        >>
        >
        > temp=NULL;
        > free(temp);
        >
        Since when are you allowed to call free(NULL)?
        Since at least 1989.

        It's a bit pointless, since it does nothing whatsoever, but it's legal.
        May be what you want is :
        free(temp);
        temp = NULL;
        Probably, yes.

        <snip>

        --
        Richard Heathfield <http://www.cpax.org.uk >
        Email: -http://www. +rjh@
        Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
        "Usenet is a strange place" - dmr 29 July 1999

        Comment

        • Keith Thompson

          #5
          Re: how to release memory?

          rahul <rahulsinner@gm ail.comwrites:
          On Jun 26, 8:20 am, "mynews" <norep...@gmail .comwrote:
          I use free() function to release memory,
          But the memory usage is still increasing.
          >
          temp=NULL;
          free(temp);
          >
          Since when are you allowed to call free(NULL)?
          May be what you want is :
          free(temp);
          temp = NULL;
          [...]

          You're certainly allowed to call free(NULL). It does nothing.

          And that's (at least part of) the problem. The memory leak occurs
          when he assigns ``temp=NULL;'', thereby losing the value of the
          pointer that he wants to free.

          There are numerous other problems, which I'll go over in a separate
          followup.

          --
          Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
          Nokia
          "We must do something. This is something. Therefore, we must do this."
          -- Antony Jay and Jonathan Lynn, "Yes Minister"

          Comment

          • pete

            #6
            Re: how to release memory?

            rahul wrote:
            Since when are you allowed to call free(NULL)?
            K&R2 is copyrighted 1988.

            Appendix B, B5, says
            "void free(void *p)
            free deallocates the space pointed to by p,
            it does nothing if p is NULL."

            --
            pete

            Comment

            • Keith Thompson

              #7
              Re: how to release memory?

              "mynews" <noreplay@gmail .comwrites:
              I use free() function to release memory,
              But the memory usage is still increasing.
              >
              cygwin
              >
              #include <stdio.h>
              #include <stdlib.h>
              #include <string.h>
              >
              struct queue{
              char data[1024];
              struct queue *next;
              };
              struct queue *myqueue[1024];
              struct queue *pre_item[1024];
              struct queue *first_item[1024];
              Three arrays of pointers seems excessive. I'm sure there's a simpler
              way to do this, but I'll just deal with C issues here.
              void enqueue(int sockfd,char *var){
              myqueue[sockfd]=(struct queue *) malloc(sizeof (struct queue));
              Don't cast the result of malloc(). The recommended idiom for this is:
              myqueue[sockfd] = malloc(sizeof *myqueue[sockfd]);
              More generally:
              ptr = malloc(sizeof *ptr);
              or
              ptr = malloc(N * sizeof *ptr);
              You can add parentheses if you like:
              ptr = malloc(sizeof(* ptr));
              strcpy((char *)&myqueue[sockfd]->data,var);
              Most casts are unnecessary. This one, I suspect, was added to
              suppress a warning. Adding a cast to supress a warning is like
              disconnecting a warning light on your car's dashboard; the problem is
              still there.

              strcpy() expects a char* as its first argument.
              ``myqueue[sockfd]->data'' is of type char[1024], which decays to
              char* in most contexts, so that's exactly what you want:

              strcpy(myqueue[sockfd]->data, var);

              What you've done is take the address of the array, which is of type
              char(*)[1024], and then forcibly converted that to the expected type.

              myqueue[sockfd]->next=NULL;
              if (pre_item[sockfd]!=NULL){
              pre_item[sockfd]->next=myqueue[sockfd];
              }else{
              first_item[sockfd]=myqueue[sockfd];
              }
              pre_item[sockfd]=myqueue[sockfd];
              }
              >
              char *dequeue(int sockfd){
              char r[1024];
              struct queue *temp;
              temp=first_item[sockfd];
              strcpy(r,temp->data);
              first_item[sockfd]=first_item[sockfd]->next;
              temp=NULL;
              free(temp);
              You need to set temp to NULL *after* calling free().

              For that matter, since temp is just about to go out of scope, there's
              no need to set it to NULL.
              return r;
              r is a local variable of type char[1024]. It decays to a pointer to
              its first element. Returning a pointer to a local variable is A Bad
              Thing. You're giving the caller a pointer to something that will
              no longer exist.
              }
              --
              Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
              Nokia
              "We must do something. This is something. Therefore, we must do this."
              -- Antony Jay and Jonathan Lynn, "Yes Minister"

              Comment

              • Bartc

                #8
                Re: how to release memory?

                Keith Thompson wrote:
                "mynews" <noreplay@gmail .comwrites:
                > temp=NULL;
                > free(temp);
                >
                You need to set temp to NULL *after* calling free().
                >
                For that matter, since temp is just about to go out of scope, there's
                no need to set it to NULL.
                It might be good practice to set temp to NULL. The code may grow in future
                or it may be copied elsewhere.

                Probably the compiler will eliminate it in this case.

                --
                Bartc


                Comment

                • Chris Dollin

                  #9
                  Re: how to release memory?

                  Bartc wrote:
                  Keith Thompson wrote:
                  >"mynews" <noreplay@gmail .comwrites:
                  >
                  >> temp=NULL;
                  >> free(temp);
                  >>
                  >You need to set temp to NULL *after* calling free().
                  >>
                  >For that matter, since temp is just about to go out of scope, there's
                  >no need to set it to NULL.
                  >
                  It might be good practice to set temp to NULL. The code may grow in future
                  or it may be copied elsewhere.
                  Or it might not. Or reading the superfluous line of code might be
                  the last straw and send some poor programmer round the twist. Or
                  the extra bytes might overflow the disc. Or Cthulhu might turn up.

                  If the code /does/ grow or get copied, then appropriate action may
                  be taken.

                  --
                  "The letter was not unproductive." /Mansfield Park/

                  Hewlett-Packard Limited Cain Road, Bracknell, registered no:
                  registered office: Berks RG12 1HN 690597 England

                  Comment

                  • pereges

                    #10
                    Re: how to release memory?

                    I also have a few doubts with regard to releasing memory and other
                    resources. When an error occurs at some point in the program then
                    usually we proceed by printing an error message and propogating a flag
                    backwards ( return (1) ) indicating error. Is it a good policy to
                    release all the resources which were held up till then (when the error
                    occured) in the program. For eg. a file may be open which must be
                    closed, a data structure that must be freed etc. It can vary at
                    different points in the program, different resources may have to be
                    freed depending on what was allocated till that point. At the very end
                    (just before main process ends) all the resources can be freed.


                    Comment

                    • santosh

                      #11
                      Re: how to release memory?

                      pereges wrote:
                      I also have a few doubts with regard to releasing memory and other
                      resources. When an error occurs at some point in the program then
                      usually we proceed by printing an error message and propogating a flag
                      backwards ( return (1) ) indicating error. Is it a good policy to
                      release all the resources which were held up till then (when the error
                      occured) in the program. For eg. a file may be open which must be
                      closed, a data structure that must be freed etc. It can vary at
                      different points in the program, different resources may have to be
                      freed depending on what was allocated till that point. At the very end
                      (just before main process ends) all the resources can be freed.
                      You have the right idea. It's always good practise to release resources
                      held after a critical failure. Modern OSes may be able to recover
                      memory even if you do not free it before the program terminates, but
                      other resources like file streams may still need flushing, and this may
                      not happen automatically during abnormal termination.

                      In C this is generally done by propagating the critical failure up the
                      call stack, with each function cleaning up it's resources, all the way
                      up to main. Of course, this is tedious and may not be practical for
                      large programs. You might find that it often easier to just exit from
                      many important functions rather than go all the way back to main for
                      every error. If you need to invariably perform certain actions at exit,
                      then you can register the concerned functions with atexit. You should
                      generally reserve abort and _Exit for serious conditions like internal
                      inconsistency.

                      Comment

                      • Barry Schwarz

                        #12
                        Re: how to release memory?

                        On Fri, 27 Jun 2008 11:11:02 GMT, "Bartc" <bc@freeuk.comw rote:
                        >
                        >"Richard Bos" <rlb@hoekstra-uitgeverij.nlwr ote in message
                        >news:4864c15b. 1215477219@news .xs4all.nl...
                        >"Bartc" <bc@freeuk.comw rote:
                        >>
                        >>Keith Thompson wrote:
                        >"mynews" <noreplay@gmail .comwrites:
                        >>>
                        >> temp=NULL;
                        >> free(temp);
                        >>
                        >You need to set temp to NULL *after* calling free().
                        >>
                        >For that matter, since temp is just about to go out of scope, there's
                        >no need to set it to NULL.
                        >>>
                        >>It might be good practice to set temp to NULL. The code may grow in
                        >>future
                        >>or it may be copied elsewhere.
                        >>
                        >It is not good practice to set pointers to null for no better reason
                        >than that one has just free()d them. It will lead you to believe that
                        >all pointers are either valid or null; and sooner or later, you will
                        >encounter one which is not.
                        >
                        >No. It just means that if accidentally a freed pointer is dereferenced, an
                        >error is raised. Otherwise it might quietly work until it causes trouble
                        >later on.
                        Dereferencing a NULL pointer will invoke undefined behavior but there
                        is no guarantee that an error will be raised.


                        Remove del for email

                        Comment

                        • Raymond Martineau

                          #13
                          Re: how to release memory?

                          On Fri, 27 Jun 2008 11:11:02 GMT, "Bartc" <bc@freeuk.comw rote:
                          >
                          >"Richard Bos" <rlb@hoekstra-uitgeverij.nlwr ote in message
                          >news:4864c15b. 1215477219@news .xs4all.nl...
                          >
                          >It is not good practice to set pointers to null for no better reason
                          >than that one has just free()d them. It will lead you to believe that
                          >all pointers are either valid or null; and sooner or later, you will
                          >encounter one which is not.
                          >
                          >No. It just means that if accidentally a freed pointer is dereferenced, an
                          >error is raised.
                          At least one platform requires you to dereference the equivalant of a
                          NULL pointer, since the BIOS stored an important table at that
                          location. If you accidently dereference said pointer and change its
                          content, you take out the system rather than raising an error.

                          When you are dealing with pointers, the rule is not to use an invalid
                          pointer for whatever reason. In the case above, setting the pointer
                          to NULL just changes how the trouble will occurr rather then stopping
                          it immediatly.

                          Comment

                          • pete

                            #14
                            Re: how to release memory?

                            Raymond Martineau wrote:
                            On Fri, 27 Jun 2008 11:11:02 GMT, "Bartc" <bc@freeuk.comw rote:
                            >
                            >"Richard Bos" <rlb@hoekstra-uitgeverij.nlwr ote in message
                            >news:4864c15b. 1215477219@news .xs4all.nl...
                            >>
                            >>It is not good practice to set pointers to null for no better reason
                            >>than that one has just free()d them. It will lead you to believe that
                            >>all pointers are either valid or null; and sooner or later, you will
                            >>encounter one which is not.
                            >No. It just means that if accidentally a freed pointer is dereferenced, an
                            >error is raised.
                            >
                            At least one platform requires you to dereference the equivalant of a
                            NULL pointer, since the BIOS stored an important table at that
                            location. If you accidently dereference said pointer and change its
                            content, you take out the system rather than raising an error.
                            >
                            When you are dealing with pointers, the rule is not to use an invalid
                            pointer for whatever reason. In the case above, setting the pointer
                            to NULL just changes how the trouble will occurr rather then stopping
                            it immediatly.
                            There's a difference between what you can do with
                            a null pointer and what you can do with an indeterminate pointer.

                            If p is not indeterminate, then (p == NULL) is defined.

                            If p has just been freed, then (p == NULL) is undefined.

                            --
                            pete

                            Comment

                            • Joe Wright

                              #15
                              Re: how to release memory?

                              pete wrote:
                              Raymond Martineau wrote:
                              >On Fri, 27 Jun 2008 11:11:02 GMT, "Bartc" <bc@freeuk.comw rote:
                              >>
                              >>"Richard Bos" <rlb@hoekstra-uitgeverij.nlwr ote in message
                              >>news:4864c15b .1215477219@new s.xs4all.nl...
                              >>>
                              >>>It is not good practice to set pointers to null for no better reason
                              >>>than that one has just free()d them. It will lead you to believe that
                              >>>all pointers are either valid or null; and sooner or later, you will
                              >>>encounter one which is not.
                              >>No. It just means that if accidentally a freed pointer is
                              >>dereference d, an error is raised.
                              >>
                              >At least one platform requires you to dereference the equivalant of a
                              >NULL pointer, since the BIOS stored an important table at that
                              >location. If you accidently dereference said pointer and change its
                              >content, you take out the system rather than raising an error.
                              >When you are dealing with pointers, the rule is not to use an invalid
                              >pointer for whatever reason. In the case above, setting the pointer
                              >to NULL just changes how the trouble will occurr rather then stopping
                              >it immediatly.
                              >
                              There's a difference between what you can do with
                              a null pointer and what you can do with an indeterminate pointer.
                              >
                              If p is not indeterminate, then (p == NULL) is defined.
                              >
                              If p has just been freed, then (p == NULL) is undefined.
                              >
                              Examining the value of a pointer (p == NULL) is defined as 0 or 1
                              depending on the value of the pointer. If 1 then p is a valid pointer to
                              NULL. Thou shalt not dereference it.

                              There is no way to know whether a non-NULL pointer is valid or
                              indeterminate by examining it. Clearly, 'free(p);' will cause the value
                              of p to be indeterminate. You can examine p until you're blue but
                              nothing about it will tell you it has been freed.

                              --
                              Joe Wright
                              "Everything should be made as simple as possible, but not simpler."
                              --- Albert Einstein ---

                              Comment

                              Working...