Memory leaking..

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

    #1

    Memory leaking..

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

    char * strclear(const char *str)
    {
    char *string;
    string=(char *)malloc(strlen (str)+1);
    strcpy(string,s tr);
    return string;
    }


    int main()
    {
    char *str="Five pineapples";
    char *string;
    string=strclear (str);
    printf ("The string is %s\n",string);
    free(string);
    return 0;
    }

    Please refer above program for my question..

    1. When i run with valgrid i got message as "16 byts in 1 block still
    reachable". I think memory is leaking in the program. Am i right?

    2. Since i assign value of heap memory starting address and calling
    free it is not freed.. why?

    3. Could you any one please tell me how can i free the memory which
    has been allocated dynamically by another function. without using any
    globel variable?

    Please help me ..
    Thanks in advance,
    Ganesh
  • Ian Collins

    #2
    Re: Memory leaking..

    gNash wrote:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    >
    char * strclear(const char *str)
    {
    char *string;
    string=(char *)malloc(strlen (str)+1);
    Please drop the cast and you may as well initialise string where it is
    declared.
    strcpy(string,s tr);
    return string;
    }
    >
    >
    int main()
    {
    char *str="Five pineapples";
    char *string;
    string=strclear (str);
    printf ("The string is %s\n",string);
    free(string);
    return 0;
    }
    >
    Please refer above program for my question..
    >
    1. When i run with valgrid i got message as "16 byts in 1 block still
    reachable". I think memory is leaking in the program. Am i right?
    >
    No.
    2. Since i assign value of heap memory starting address and calling
    free it is not freed.. why?
    >
    It is freed.

    --
    Ian Collins.

    Comment

    • Richard Heathfield

      #3
      Re: Memory leaking..

      gNash said:
      #include <stdio.h>
      #include <string.h>
      #include <stdlib.h>
      >
      char * strclear(const char *str)
      {
      char *string;
      string=(char *)malloc(strlen (str)+1);
      strcpy(string,s tr);
      return string;
      }
      Better (or at least different!):

      char *clearstr(const char *str) /* [1] */
      {
      size_t len = strlen(str) + 1; /* [2] */
      char *string = malloc(len); /* [3] */
      if(string != NULL) /* [4] */
      {
      memcpy(string, str, len); /* [5] */
      }
      return string;
      }

      [1] - str followed by a-z is "reserved for external use" by the
      implementation, so don't use it in your own function names.
      [2] - nesting the strlen in the malloc is fine, but if you choose to go the
      memcpy route (see [5]), you'll want to cache this value.
      [3] - no need to cast the return value of malloc, although *in this case*
      your cast did no actual damage concealment, since you remembered to
      #include <stdlib.h>, so no harm done on this occasion.
      [4] - malloc can fail. Check that it doesn't before trusting the result.
      [5] - if logic were any guide, it would make sense for memcpy to perform
      the copy faster than strcpy. In practice, it seems to depend on the
      implementation and to some extent on the length of the string. So this and
      the preparatory step [2], above, are the bits that I'm simply mentioning
      for consideration, rather than positively recommending.

      int main()
      {
      char *str="Five pineapples";
      char *string;
      string=strclear (str);
      See [1] above.
      printf ("The string is %s\n",string);
      Check for NULL:

      if(string != NULL)
      {
      printf("The string is %s\n", string);
      free(string);
      }

      <snip>
      1. When i run with valgrid i got message as "16 byts in 1 block still
      reachable". I think memory is leaking in the program. Am i right?
      The program you showed has no leak.
      2. Since i assign value of heap memory starting address and calling
      free it is not freed.. why?
      The program has no mechanism to detect whether that claim is correct.
      3. Could you any one please tell me how can i free the memory which
      has been allocated dynamically by another function. without using any
      globel variable?
      You already know how to do it. You've already done it. If valgrind is
      behaving as you say on the program you show, then valgrind is wrong or
      your implementation is sub-optimal.

      --
      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

      • gNash

        #4
        Re: Memory leaking..

        On Nov 15, 12:04 pm, Ian Collins <ian-n...@hotmail.co mwrote:
        gNash wrote:
        #include <stdio.h>
        #include <string.h>
        #include <stdlib.h>
        >
        char * strclear(const char *str)
        {
        char *string;
        string=(char *)malloc(strlen (str)+1);
        >
        Please drop the cast and you may as well initialise string where it is
        declared.
        >
        >
        >
        strcpy(string,s tr);
        return string;
        }
        >
        int main()
        {
        char *str="Five pineapples";
        char *string;
        string=strclear (str);
        printf ("The string is %s\n",string);
        free(string);
        return 0;
        }
        >
        Please refer above program for my question..
        >
        1. When i run with valgrid i got message as "16 byts in 1 block still
        reachable". I think memory is leaking in the program. Am i right?
        >
        No.
        >
        2. Since i assign value of heap memory starting address and calling
        free it is not freed.. why?
        >
        It is freed.
        >
        --
        Ian Collins.

        Thankyou Ian Collins.. but i not getting message from valgrind as "all
        heap memory are freed " it is saying "16 bytes are still reachable "
        what it mean?

        Please explain me..

        Comment

        • Ian Collins

          #5
          Re: Memory leaking..

          gNash wrote:
          On Nov 15, 12:04 pm, Ian Collins <ian-n...@hotmail.co mwrote:
          >--
          >Ian Collins.
          >
          *Please* don't quote signatures.
          >
          Thankyou Ian Collins.. but i not getting message from valgrind as "all
          heap memory are freed " it is saying "16 bytes are still reachable "
          what it mean?
          >
          Please explain me..
          I've no idea, never having used valgrind. All I can say is it is wrong.

          --
          Ian Collins.

          Comment

          • gNash

            #6
            Re: Memory leaking..

            On Nov 15, 12:14 pm, Richard Heathfield <r...@see.sig.i nvalidwrote:
            gNash said:
            >
            #include <stdio.h>
            #include <string.h>
            #include <stdlib.h>
            >
            char * strclear(const char *str)
            {
            char *string;
            string=(char *)malloc(strlen (str)+1);
            strcpy(string,s tr);
            return string;
            }
            >
            Better (or at least different!):
            >
            char *clearstr(const char *str) /* [1] */
            {
            size_t len = strlen(str) + 1; /* [2] */
            char *string = malloc(len); /* [3] */
            if(string != NULL) /* [4] */
            {
            memcpy(string, str, len); /* [5] */
            }
            return string;
            >
            }
            >
            [1] - str followed by a-z is "reserved for external use" by the
            implementation, so don't use it in your own function names.
            [2] - nesting the strlen in the malloc is fine, but if you choose to go the
            memcpy route (see [5]), you'll want to cache this value.
            [3] - no need to cast the return value of malloc, although *in this case*
            your cast did no actual damage concealment, since you remembered to
            #include <stdlib.h>, so no harm done on this occasion.
            [4] - malloc can fail. Check that it doesn't before trusting the result.
            [5] - if logic were any guide, it would make sense for memcpy to perform
            the copy faster than strcpy. In practice, it seems to depend on the
            implementation and to some extent on the length of the string. So this and
            the preparatory step [2], above, are the bits that I'm simply mentioning
            for consideration, rather than positively recommending.
            >
            int main()
            {
            char *str="Five pineapples";
            char *string;
            string=strclear (str);
            >
            See [1] above.
            >
            printf ("The string is %s\n",string);
            >
            Check for NULL:
            >
            if(string != NULL)
            {
            printf("The string is %s\n", string);
            free(string);
            >
            }
            >
            <snip>
            >
            1. When i run with valgrid i got message as "16 byts in 1 block still
            reachable". I think memory is leaking in the program. Am i right?
            >
            The program you showed has no leak.
            >
            2. Since i assign value of heap memory starting address and calling
            free it is not freed.. why?
            >
            The program has no mechanism to detect whether that claim is correct.
            >
            3. Could you any one please tell me how can i free the memory which
            has been allocated dynamically by another function. without using any
            globel variable?
            >
            You already know how to do it. You've already done it. If valgrind is
            behaving as you say on the program you show, then valgrind is wrong or
            your implementation is sub-optimal.
            >
            --
            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
            thanks a lot Mr. Richared Heathfield. thanks for your information for
            [1] too.

            Comment

            • Nick Keighley

              #7
              Re: Memory leaking..

              Richard Heathfield wrote:

              <snip>
              Better (or at least different!):
              >
              char *clearstr(const char *str) /* [1] */
              {
              size_t len = strlen(str) + 1; /* [2] */
              char *string = malloc(len); /* [3] */
              if(string != NULL) /* [4] */
              {
              memcpy(string, str, len); /* [5] */
              where does string get terminated?

              }
              return string;
              }
              <snip>

              If I want to copy a string I use strcpy(). That way I avoid failing to
              put the nul terminator in...


              --
              Nick Keighley

              Comment

              • Mark Bluemel

                #8
                Re: Memory leaking..

                Nick Keighley wrote:
                Richard Heathfield wrote:
                >
                <snip>
                >
                >Better (or at least different!):
                >>
                >char *clearstr(const char *str) /* [1] */
                >{
                > size_t len = strlen(str) + 1; /* [2] */
                > char *string = malloc(len); /* [3] */
                > if(string != NULL) /* [4] */
                > {
                > memcpy(string, str, len); /* [5] */
                >
                where does string get terminated?
                What is the value of len?

                Comment

                • Nick Keighley

                  #9
                  Re: Memory leaking..

                  Mark Bluemel wrote:
                  Nick Keighley wrote:
                  Richard Heathfield wrote:

                  <snip>
                  Better (or at least different!):
                  >
                  char *clearstr(const char *str) /* [1] */
                  {
                  size_t len = strlen(str) + 1; /* [2] */
                  char *string = malloc(len); /* [3] */
                  if(string != NULL) /* [4] */
                  {
                  memcpy(string, str, len); /* [5] */
                  where does string get terminated?
                  >
                  What is the value of len?
                  brain fart. it wasn't the value of len that fooled me,
                  I failed to realise that its copying an already correctly
                  terminated string.

                  And I realised that about 1ns *after* I hit the post button.

                  <mumbleI *still* think strcpy() is better </mumble>


                  --
                  Nick Keighley

                  Comment

                  • Chris Dollin

                    #10
                    Re: Memory leaking..

                    Nick Keighley wrote:
                    Richard Heathfield wrote:
                    >
                    <snip>
                    >
                    >Better (or at least different!):
                    >>
                    >char *clearstr(const char *str) /* [1] */
                    >{
                    > size_t len = strlen(str) + 1; /* [2] */
                    > char *string = malloc(len); /* [3] */
                    > if(string != NULL) /* [4] */
                    > {
                    > memcpy(string, str, len); /* [5] */
                    >
                    where does string get terminated?
                    In the `memcpy`, which copies `len` bytes, where `len` is /one more than/
                    the length of the string and hence includes the nul byte. This is also
                    why the `malloc` allocates enough space for the entire terminated string.

                    --
                    Chris "make room! make room!" Dollin

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

                    Comment

                    • Chris Dollin

                      #11
                      Re: Memory leaking..

                      Nick Keighley wrote:
                      And I realised that about 1ns *after* I hit the post button.
                      Ha! I realise things like that /as I press the button/!

                      I win! Wait ... that's a good thing, right? (fx:post) Oops.

                      --
                      Chris "really really /really/ fast heartbeat" Dollin

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

                      Comment

                      • dSpam@arcor.de

                        #12
                        Re: Memory leaking..

                        On 15 Nov., 08:20, Ian Collins <ian-n...@hotmail.co mwrote:
                        gNash wrote:
                        what it mean?
                        >
                        I've no idea, never having used valgrind. All I can say is it is wrong.
                        If you've no idea what something means, you cannot know that it is
                        wrong. (But of course you can say it regardless.)

                        Comment

                        • Ben Bacarisse

                          #13
                          Re: Memory leaking..

                          gNash <ganeshamutha@g mail.comwrites:

                          <snip program>
                          1. When i run with valgrid i got message as "16 byts in 1 block still
                          reachable". I think memory is leaking in the program. Am i right?
                          No, and if I copy, compile and run your code on my system, valgrind
                          says:

                          ==7667== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
                          ==7667== malloc/free: in use at exit: 0 bytes in 0 blocks.
                          ==7667== malloc/free: 1 allocs, 1 frees, 16 bytes allocated.
                          ==7667== For counts of detected errors, rerun with: -v
                          ==7667== All heap blocks were freed -- no leaks are possible.

                          so you are chasing a phantom problem. There is none.

                          --
                          Ben.

                          Comment

                          • Richard

                            #14
                            Re: Memory leaking..

                            "dSpam@arcor.de " <dSpam@arcor.de writes:
                            On 15 Nov., 08:20, Ian Collins <ian-n...@hotmail.co mwrote:
                            >gNash wrote:
                            what it mean?
                            >>
                            >I've no idea, never having used valgrind. All I can say is it is wrong.
                            >
                            If you've no idea what something means, you cannot know that it is
                            wrong. (But of course you can say it regardless.)
                            He was referring to the non pertinent parts of the program being "wrong"
                            - well not standard C. The cast did nothing wrong with regard to the
                            rest of the program. The moving of the malloc to the declaration line
                            was equally as non contributory to the question but simply made for
                            tighter cleaner code.

                            Comment

                            • Kenneth Brody

                              #15
                              Re: Memory leaking..

                              gNash wrote:
                              >
                              On Nov 15, 12:04 pm, Ian Collins <ian-n...@hotmail.co mwrote:
                              gNash wrote:
                              [... snip code ...]
                              Please refer above program for my question..
                              1. When i run with valgrid i got message as "16 byts in 1 block still
                              reachable". I think memory is leaking in the program. Am i right?
                              No.
                              2. Since i assign value of heap memory starting address and calling
                              free it is not freed.. why?
                              It is freed.
                              >
                              Thankyou Ian Collins.. but i not getting message from valgrind as "all
                              heap memory are freed " it is saying "16 bytes are still reachable "
                              what it mean?
                              >
                              Please explain me..
                              I've never used valgrind, but...

                              The code you posted frees everything that it mallocs.

                              Is it possible that the runtime startup code allocated something
                              that wasn't freed, and it's this block that's being reported?

                              --
                              +-------------------------+--------------------+-----------------------+
                              | Kenneth J. Brody | www.hvcomputer.com | #include |
                              | kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
                              +-------------------------+--------------------+-----------------------+
                              Don't e-mail me at: <mailto:ThisIsA SpamTrap@gmail. com>


                              Comment

                              Working...