Structure having pointers

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • sam_cit@yahoo.co.in

    Structure having pointers

    Hi,

    I have the following Struct,

    Struct Sample
    {
    int i;
    char *p;
    };

    int main()
    {
    Sample a;
    a.p = malloc(10);
    Sample b;
    b = a;
    }

    Now i think a shallow copy is done and if i destry only on the object
    there would be a dangling pointer.
    How do i overcome this problem as C structures don't support
    functions?

    Thanks in advance!!!

  • AnticitizenOne

    #2
    Re: Structure having pointers

    Hi,
    when you write b=a you copy the memory of the struct instance a in b.
    In this way you copy the pointer p of a in b. Now a.p and b.p point to
    the same memory.
    To make a depth copy of the struct you have to write a function:

    struct Sample* SampleCopy(stru ct Sample* src)
    {
    struct Sample* b=NULL;
    b=(struct Sample*)malloc( sizeof(struct Sample));
    b.i=src.i;
    b.p=(char*)mall oc(sizeof(char) *(strlen(src.p) +1));
    memcpy(b.p,src. p);
    return b;
    }

    int main()
    {
    Sample a;
    a.p = (char*)malloc(1 0);
    Sample *b;
    b = SampleCopy(&a);

    free(a.p);
    free(a);
    printf("%s",b->p); //should work!!
    }

    I think in this way you may solve your problem... if I've understood.
    Probably I've committed some errors in the code.. but I've not a
    reference now!

    Bye
    Gio


    On 29 Lug, 12:20, sam_...@yahoo.c o.in wrote:
    Hi,
    >
    I have the following Struct,
    >
    Struct Sample
    {
    int i;
    char *p;
    };
    >
    int main()
    {
    Sample a;
    a.p = malloc(10);
    Sample b;
    b = a;
    >
    }
    >
    Now i think a shallow copy is done and if i destry only on the object
    there would be a dangling pointer.
    How do i overcome this problem as C structures don't support
    functions?
    >
    Thanks in advance!!!


    Comment

    • santosh

      #3
      Re: Structure having pointers

      sam_cit@yahoo.c o.in wrote:
      Hi,
      >
      I have the following Struct,
      >
      Struct Sample
      The keyword is struct, not Struct. C is case sensitive.
      {
      int i;
      char *p;
      };
      >
      int main()
      {
      Sample a;
      The declaration should be:

      struct Sample a;
      a.p = malloc(10);
      Sample b;
      As above.
      b = a;
      }
      >
      Now i think a shallow copy is done
      Since a.i has an indeterminate value, the copy invokes undefined behaviour.
      and if i destry only on the object
      there would be a dangling pointer.
      How do i overcome this problem as C structures don't support
      functions?
      Deallocate the memory by calling free on either a.p or b.p, and set them
      both to NULL.

      Comment

      • santosh

        #4
        Re: Structure having pointers

        AnticitizenOne wrote:

        [top-post corrected]
        On 29 Lug, 12:20, sam_...@yahoo.c o.in wrote:
        >Hi,
        >>
        > I have the following Struct,
        >>
        > Struct Sample
        > {
        > int i;
        > char *p;
        > };
        >>
        >int main()
        >{
        > Sample a;
        > a.p = malloc(10);
        > Sample b;
        > b = a;
        >>
        >}
        >>
        > Now i think a shallow copy is done and if i destry only on the object
        >there would be a dangling pointer.
        >How do i overcome this problem as C structures don't support
        >functions?
        >
        Hi,
        when you write b=a you copy the memory of the struct instance a in b.
        In this way you copy the pointer p of a in b. Now a.p and b.p point to
        the same memory.
        To make a depth copy of the struct you have to write a function:
        >
        struct Sample* SampleCopy(stru ct Sample* src)
        {
        struct Sample* b=NULL;
        b=(struct Sample*)malloc( sizeof(struct Sample));
        The cast isn't recommended in C.
        b.i=src.i;
        b.p=(char*)mall oc(sizeof(char) *(strlen(src.p) +1));
        And sizeof(char) is always one in C.
        memcpy(b.p,src. p);
        return b;
        }
        >
        int main()
        {
        Sample a;
        It should be struct Sample a;
        a.p = (char*)malloc(1 0);
        Sample *b;
        Mixed code and declarations are not allowed in C89 though they're allowed in
        C99.
        b = SampleCopy(&a);
        >
        free(a.p);
        free(a);
        printf("%s",b->p); //should work!!
        return 0;
        }

        Comment

        • Malcolm McLean

          #5
          Re: Structure having pointers


          <sam_cit@yahoo. co.inwrote in message
          news:1185704400 .274756.296890@ i38g2000prf.goo glegroups.com.. .
          Hi,
          >
          I have the following Struct,
          >
          Struct Sample
          {
          int i;
          char *p;
          };
          >
          int main()
          {
          Sample a;
          a.p = malloc(10);
          Sample b;
          b = a;
          }
          >
          Now i think a shallow copy is done and if i destry only on the object
          there would be a dangling pointer.
          How do i overcome this problem as C structures don't support
          functions?
          >
          Thanks in advance!!!
          >
          Do it like this

          struct Sample *sample(int N)
          {
          struct Sample *answer;
          answer = malloc(sizeof(s truct Sample));
          if(!answer)
          goto error_exit;
          answer.p = malloc(N);
          if(!answer.p)
          goto error_exit;
          return answer;
          error_exit:
          killSample(answ er);
          return 0;
          }

          void killSample(stru ct Sample *s)
          {
          if(s)
          {
          free(s.p);
          free(s);
          }
          }

          struct Sample *Sample_clone(s truct Sample *s)
          {
          struct Sample *answer;

          answer = sample(s.N):
          if(!answer)
          return 0;
          memcpy(answer.p , s.p, s.N);
          return answer;
          }

          All we are doing is replacing member functions with fucntions which take a
          struct Sample * as a parameter. For simplicity everything is kept in dynamic
          memory - very rarely this will cause a performance problem and need to be
          changed - but it simpifies the code management.

          --
          Free games and programming goodies.


          Comment

          • Richard Heathfield

            #6
            Re: Structure having pointers

            sam_cit@yahoo.c o.in said:
            Hi,
            >
            I have the following Struct,
            >
            Struct Sample
            {
            int i;
            char *p;
            };
            >
            int main()
            {
            Sample a;
            a.p = malloc(10);
            Sample b;
            b = a;
            }
            In addition to other people's comments, I would point out that this code
            is not legal in either C90 or C99. The absence of a function declarator
            for malloc requires a diagnostic message under the rules of either
            Standard, and the mixing of declarations with code requires a
            diagnostic message under C90.

            I suggest you increase your compiler's level of diagnostic checking
            until it conforms with the Standard's requirements.

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

            Comment

            • AnticitizenOne

              #7
              Re: Structure having pointers

              On 29 Lug, 14:04, santosh <santosh....@gm ail.comwrote:
              AnticitizenOne wrote:
              >
              [top-post corrected]
              >
              >
              >
              On 29 Lug, 12:20, sam_...@yahoo.c o.in wrote:
              Hi,
              >
              I have the following Struct,
              >
              Struct Sample
              {
              int i;
              char *p;
              };
              >
              int main()
              {
              Sample a;
              a.p = malloc(10);
              Sample b;
              b = a;
              >
              }
              >
              Now i think a shallow copy is done and if i destry only on the object
              there would be a dangling pointer.
              How do i overcome this problem as C structures don't support
              functions?
              >
              Hi,
              when you write b=a you copy the memory of the struct instance a in b.
              In this way you copy the pointer p of a in b. Now a.p and b.p point to
              the same memory.
              To make a depth copy of the struct you have to write a function:
              >
              struct Sample* SampleCopy(stru ct Sample* src)
              {
              struct Sample* b=NULL;
              b=(struct Sample*)malloc( sizeof(struct Sample));
              >
              The cast isn't recommended in C.
              >
              b.i=src.i;
              b.p=(char*)mall oc(sizeof(char) *(strlen(src.p) +1));
              >
              And sizeof(char) is always one in C.
              >
              memcpy(b.p,src. p);
              return b;
              }
              >
              int main()
              {
              Sample a;
              >
              It should be struct Sample a;
              >
              a.p = (char*)malloc(1 0);
              Sample *b;
              >
              Mixed code and declarations are not allowed in C89 though they're allowed in
              C99.
              >
              b = SampleCopy(&a);
              >
              free(a.p);
              free(a);
              printf("%s",b->p); //should work!!
              >
              return 0;
              >
              }
              Sorry for my errors... 90% of them are for distraction and cut'n
              paste...
              b=(struct Sample*)malloc( sizeof(struct Sample));
              >
              The cast isn't recommended in C.
              >
              This is really new for me o_O
              I use the cast a lot... why in C is not recommended?

              thanks!
              bye
              Gio

              Comment

              • Richard Heathfield

                #8
                Re: Structure having pointers

                AnticitizenOne said:
                On 29 Lug, 14:04, santosh <santosh....@gm ail.comwrote:
                >AnticitizenO ne wrote:
                <snip>
                b=(struct Sample*)malloc( sizeof(struct Sample));
                >>
                >The cast isn't recommended in C.
                >>
                This is really new for me o_O
                I use the cast a lot...
                Why?
                why in C is not recommended?
                Several reasons, but before we get into those reasons, let's find out
                your reasons for using the cast.

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

                Comment

                • Richard

                  #9
                  Re: Structure having pointers

                  santosh <santosh.k83@gm ail.comwrites:
                  sam_cit@yahoo.c o.in wrote:
                  >
                  >Hi,
                  >>
                  > I have the following Struct,
                  >>
                  > Struct Sample
                  >
                  The keyword is struct, not Struct. C is case sensitive.
                  >
                  > {
                  > int i;
                  > char *p;
                  > };
                  >>
                  >int main()
                  >{
                  > Sample a;
                  >
                  The declaration should be:
                  >
                  struct Sample a;
                  >
                  > a.p = malloc(10);
                  > Sample b;
                  >
                  As above.
                  >
                  > b = a;
                  >}
                  >>
                  > Now i think a shallow copy is done
                  >
                  Since a.i has an indeterminate value, the copy invokes undefined
                  behaviour.
                  How?
                  >
                  > and if i destry only on the object
                  >there would be a dangling pointer.
                  >How do i overcome this problem as C structures don't support
                  >functions?
                  >
                  Deallocate the memory by calling free on either a.p or b.p, and set them
                  both to NULL.
                  >
                  --

                  Comment

                  • AnticitizenOne

                    #10
                    Re: Structure having pointers

                    On 29 Lug, 14:39, Richard Heathfield <r...@see.sig.i nvalidwrote:
                    AnticitizenOne said:
                    >
                    On 29 Lug, 14:04, santosh <santosh....@gm ail.comwrote:
                    AnticitizenOne wrote:
                    >
                    <snip>
                    >
                    b=(struct Sample*)malloc( sizeof(struct Sample));
                    >
                    The cast isn't recommended in C.
                    >
                    This is really new for me o_O
                    I use the cast a lot...
                    >
                    Why?
                    >
                    why in C is not recommended?
                    >
                    Several reasons, but before we get into those reasons, let's find out
                    your reasons for using the cast.
                    >
                    --
                    Richard Heathfield <http://www.cpax.org.uk >
                    Email: -www. +rjh@
                    Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
                    "Usenet is a strange place" - dmr 29 July 1999
                    I use the cast as referenced in C-Language (Kerningan & Ritchie)

                    Comment

                    • santosh

                      #11
                      Re: Structure having pointers

                      AnticitizenOne wrote:
                      On 29 Lug, 14:39, Richard Heathfield <r...@see.sig.i nvalidwrote:
                      >AnticitizenO ne said:
                      >>
                      On 29 Lug, 14:04, santosh <santosh....@gm ail.comwrote:
                      >AnticitizenO ne wrote:
                      >>
                      ><snip>
                      >>
                      b=(struct Sample*)malloc( sizeof(struct Sample));
                      >>
                      >The cast isn't recommended in C.
                      >>
                      This is really new for me o_O
                      I use the cast a lot...
                      >>
                      >Why?
                      >>
                      why in C is not recommended?
                      >>
                      >Several reasons, but before we get into those reasons, let's find out
                      >your reasons for using the cast.
                      >
                      I use the cast as referenced in C-Language (Kerningan & Ritchie)
                      That book was written before the first Standard for C was published. At that
                      point, there was no void * as a generic pointer type, but instead that
                      purpose was served by the char * type. Since then it's not necessary in C
                      to cast between a void * and another pointer type. Any pointer can be
                      converted to a void * and back again without any loss of information.

                      Infact casting the return value of malloc can prevent your compiler from
                      warning you when you fail to include stdlib.h, which declares malloc's
                      prototype. This can lead to possible undefined behaviour.

                      The only real reason for casting the return of malloc in C is if you're
                      forced to compile it under a C++ compiler or in a mixed C and C++
                      environment. That's pretty rare.

                      Comment

                      • AnticitizenOne

                        #12
                        Re: Structure having pointers

                        On 29 Lug, 14:53, santosh <santosh....@gm ail.comwrote:
                        AnticitizenOne wrote:
                        On 29 Lug, 14:39, Richard Heathfield <r...@see.sig.i nvalidwrote:
                        AnticitizenOne said:
                        >
                        On 29 Lug, 14:04, santosh <santosh....@gm ail.comwrote:
                        AnticitizenOne wrote:
                        >
                        <snip>
                        >
                        b=(struct Sample*)malloc( sizeof(struct Sample));
                        >
                        The cast isn't recommended in C.
                        >
                        This is really new for me o_O
                        I use the cast a lot...
                        >
                        Why?
                        >
                        why in C is not recommended?
                        >
                        Several reasons, but before we get into those reasons, let's find out
                        your reasons for using the cast.
                        >
                        I use the cast as referenced in C-Language (Kerningan & Ritchie)
                        >
                        That book was written before the first Standard for C was published. At that
                        point, there was no void * as a generic pointer type, but instead that
                        purpose was served by the char * type. Since then it's not necessary in C
                        to cast between a void * and another pointer type. Any pointer can be
                        converted to a void * and back again without any loss of information.
                        >
                        Infact casting the return value of malloc can prevent your compiler from
                        warning you when you fail to include stdlib.h, which declares malloc's
                        prototype. This can lead to possible undefined behaviour.
                        >
                        The only real reason for casting the return of malloc in C is if you're
                        forced to compile it under a C++ compiler or in a mixed C and C++
                        environment. That's pretty rare.
                        uh! Thanks! I've understood.

                        Comment

                        • pete

                          #13
                          Re: Structure having pointers

                          Richard wrote:
                          >
                          santosh <santosh.k83@gm ail.comwrites:
                          >
                          sam_cit@yahoo.c o.in wrote:
                          Hi,
                          >
                          I have the following Struct,
                          >
                          Struct Sample
                          The keyword is struct, not Struct. C is case sensitive.
                          {
                          int i;
                          char *p;
                          };
                          >
                          int main()
                          {
                          Sample a;
                          The declaration should be:

                          struct Sample a;
                          a.p = malloc(10);
                          Sample b;
                          As above.
                          b = a;
                          }
                          >
                          Now i think a shallow copy is done
                          Since a.i has an indeterminate value, the copy invokes undefined
                          behaviour.
                          >
                          How?
                          Simply and obviously.

                          --
                          pete

                          Comment

                          • Ben Bacarisse

                            #14
                            Re: Structure having pointers

                            "Malcolm McLean" <regniztar@btin ternet.comwrite s:
                            <sam_cit@yahoo. co.inwrote in message
                            news:1185704400 .274756.296890@ i38g2000prf.goo glegroups.com.. .
                            >Hi,
                            >>
                            >I have the following Struct,
                            >>
                            >Struct Sample
                            >{
                            > int i;
                            > char *p;
                            >};
                            >>
                            >int main()
                            >{
                            >Sample a;
                            >a.p = malloc(10);
                            >Sample b;
                            >b = a;
                            >}
                            >>
                            >Now i think a shallow copy is done and if i destry only on the object
                            >there would be a dangling pointer.
                            >How do i overcome this problem as C structures don't support
                            >functions?
                            >>
                            Do it like this
                            >
                            struct Sample *sample(int N)
                            {
                            struct Sample *answer;
                            answer = malloc(sizeof(s truct Sample));
                            if(!answer)
                            goto error_exit;
                            answer.p = malloc(N);
                            if(!answer.p)
                            goto error_exit;
                            return answer;
                            error_exit:
                            killSample(answ er);
                            return 0;
                            }
                            >
                            void killSample(stru ct Sample *s)
                            {
                            if(s)
                            {
                            free(s.p);
                            free(s);
                            }
                            }
                            >
                            struct Sample *Sample_clone(s truct Sample *s)
                            {
                            struct Sample *answer;
                            >
                            answer = sample(s.N):
                            if(!answer)
                            return 0;
                            memcpy(answer.p , s.p, s.N);
                            return answer;
                            }
                            Depending on how you count them, you have about 8 errors and a rather
                            complex way of doing things. I would write:

                            struct Sample *sample_clone(s truct Sample *sp)
                            {
                            struct Sample *answer = malloc(sizeof *answer);
                            if (answer && (answer->p = malloc(sp->i)))
                            memcpy(answer->p, sp->p, sp->i);
                            else {
                            free(answer);
                            answer = NULL;
                            }
                            return answer;
                            }

                            void sample_kill(str uct Sample *sp)
                            {
                            if (sp) free(sp->p);
                            free(sp);
                            }

                            I know that many people don't like this style, but I think C works
                            that way. I am sure that it is not accidental that things like short
                            circuit &&, assignments in conditionals, and being able to free NULL all
                            work together to make compact, idiomatic code.

                            --
                            Ben.

                            Comment

                            • Richard

                              #15
                              Re: Structure having pointers

                              pete <pfiland@mindsp ring.comwrites:
                              Richard wrote:
                              >>
                              >santosh <santosh.k83@gm ail.comwrites:
                              >>
                              sam_cit@yahoo.c o.in wrote:
                              >
                              >Hi,
                              >>
                              > I have the following Struct,
                              >>
                              > Struct Sample
                              >
                              The keyword is struct, not Struct. C is case sensitive.
                              >
                              > {
                              > int i;
                              > char *p;
                              > };
                              >>
                              >int main()
                              >{
                              > Sample a;
                              >
                              The declaration should be:
                              >
                              struct Sample a;
                              >
                              > a.p = malloc(10);
                              > Sample b;
                              >
                              As above.
                              >
                              > b = a;
                              >}
                              >>
                              > Now i think a shallow copy is done
                              >
                              Since a.i has an indeterminate value, the copy invokes undefined
                              behaviour.
                              >>
                              >How?
                              >
                              Simply and obviously.
                              I think I have my dumb head on today Aunt Sally.

                              Really, how does the copy invoke undefined behaviour?

                              An undefined value is copied, but how does the invoke undefined
                              behaviour at the point of the copy?

                              Comment

                              Working...