Pointer initialization question...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • No Such Luck

    #1

    Pointer initialization question...

    Hi all:

    Below are two pieces of code that basically perform the same task.
    Version A produces a segmentation fault, while version B works
    correctly. I understand why version B works correctly, but I do not
    understand why version A does not work. It seems to me that in Version
    A, a pointer to an array of integers is passed as a parameter to
    init_array, and whether that pointer is NULL or not, is should be
    initialized as a new array of integers.

    Can anyone elaborate? Thanks.

    ---------Version A (Seg Fault)--------

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

    void init_array (int * array, int num)
    {
    array = (int *)malloc(sizeof (int) * num);
    }

    int main ()
    {
    int array_size = 5;
    int * array;
    init_array(arra y, array_size);
    array[3] = 10; /* This causes a segmentation fault */
    return 1;
    }

    ---------Version B (Works Correctly)--------

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

    int * init_array (int num)
    {
    int * array;
    array = (int *)malloc(sizeof (int) * num);
    return array;
    }

    int main ()
    {
    int array_size = 5;
    int * array;
    array = init_array(arra y_size);
    array[3] = 10;
    return 1;
    }

  • SnaiL

    #2
    Re: Pointer initialization question...

    Hey, in version "A" the pointer to the array was not initialized
    anyway! Try this:

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

    void init_array (int ** array, int num)
    {
    *array = (int *)malloc(sizeof (int) * num);
    }

    int main ()
    {
    int array_size = 5;
    int * array;
    init_array(&arr ay, array_size);
    array[3] = 10; /* This will not causes a segmentation fault */
    return 1;
    }


    // BTW: you must to pass a hard link to the pointer to initialize it,
    but not a copy of the pointer. When you passing a copy of the pointer,
    the pointer will only be initialized in the scope of the init_array
    function.

    Sorry for my bad English.

    Comment

    • dandelion

      #3
      Re: Pointer initialization question...


      "No Such Luck" <no_suchluck@ho tmail.com> wrote in message
      news:1104136193 .228648.23960@z 14g2000cwz.goog legroups.com...[color=blue]
      > Hi all:
      >
      > Below are two pieces of code that basically perform the same task.
      > Version A produces a segmentation fault, while version B works
      > correctly. I understand why version B works correctly, but I do not
      > understand why version A does not work. It seems to me that in Version
      > A, a pointer to an array of integers is passed as a parameter to
      > init_array, and whether that pointer is NULL or not, is should be
      > initialized as a new array of integers.
      >
      > Can anyone elaborate? Thanks.
      >
      > ---------Version A (Seg Fault)--------
      >
      > #include <stdio.h>
      > #include <stdlib.h>
      >
      > void init_array (int * array, int num)
      > {
      > array = (int *)malloc(sizeof (int) * num);[/color]

      1. Remove "(int *)". It's not neccesary and may obscure other errors
      (missing #include <stdlib.h>).
      2. If you want to return a pointer through "array" make it an "int **array"
      and assign to *array.
      Right now, your newly allocated pointer is lost when your program leaves
      the init_array scope.
      [color=blue]
      > }
      >
      > int main ()
      > {
      > int array_size = 5;
      > int * array;
      > init_array(arra y, array_size);
      > array[3] = 10; /* This causes a segmentation fault */[/color]

      No wonder. int* array is never initialized. See (2) above.
      [color=blue]
      > return 1;
      > }
      >
      > ---------Version B (Works Correctly)--------
      >
      > #include <stdio.h>
      > #include <stdlib.h>
      >
      > int * init_array (int num)
      > {
      > int * array;
      > array = (int *)malloc(sizeof (int) * num);
      > return array;
      > }[/color]

      See(1) above. Now arry *is* properly returned and "hey, presto!" your
      program works.

      <snip>


      Comment

      • Martin Ambuhl

        #4
        Re: Pointer initialization question...

        No Such Luck wrote:[color=blue]
        > Hi all:
        >
        > Below are two pieces of code that basically perform the same task.
        > Version A produces a segmentation fault, while version B works
        > correctly. I understand why version B works correctly, but I do not
        > understand why version A does not work.[/color]

        This is fully covered in the FAQ, as are the proper return values from
        main (yours isn't one of them). Please check the FAQ before posting.
        And learn to indent your code.

        In the meantime, compare the following to your code:

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

        void init_arrayA(int **a, int num)
        {
        *a = malloc(num * sizeof **a);
        }
        int *init_arrayB(in t num)
        {
        int *a;
        a = malloc(num * sizeof *a);
        return a;
        }

        int main()
        {
        int array_size = 5;
        int *array;
        init_arrayA(&ar ray, array_size);
        if (!array)
        fprintf(stderr, "malloc (A) failed\n");
        else {
        array[3] = 10;
        printf("array[3] (A) = %d\n", array[3]);
        free(array);
        }
        if (!(array = init_arrayB(arr ay_size)))
        fprintf(stderr, "malloc (B) failed\n");
        else {
        array[3] = 12;
        printf("array[3] (B) = %d\n", array[3]);
        free(array);
        }
        return 0;
        }


        array[3] (A) = 10
        array[3] (B) = 12

        [color=blue]
        > Can anyone elaborate? Thanks.[/color]

        We really shouldn't. Encouraging people to misbehave by posting
        questions without checking the FAQ and following the newsgroup first is
        a bad idea.

        [OP's code]
        [color=blue]
        > #include <stdio.h>
        > #include <stdlib.h>
        >
        > void init_array (int * array, int num)
        > {
        > array = (int *)malloc(sizeof (int) * num);
        > }
        >
        > int main ()
        > {
        > int array_size = 5;
        > int * array;
        > init_array(arra y, array_size);
        > array[3] = 10; /* This causes a segmentation fault */
        > return 1;
        > }
        >
        > ---------Version B (Works Correctly)--------
        >
        > #include <stdio.h>
        > #include <stdlib.h>
        >
        > int * init_array (int num)
        > {
        > int * array;
        > array = (int *)malloc(sizeof (int) * num);
        > return array;
        > }
        >
        > int main ()
        > {
        > int array_size = 5;
        > int * array;
        > array = init_array(arra y_size);
        > array[3] = 10;
        > return 1;
        > }
        >[/color]

        Comment

        • No Such Luck

          #5
          Re: Pointer initialization question...


          Martin Ambuhl wrote:[color=blue]
          > No Such Luck wrote:[color=green]
          > > Hi all:
          > >
          > > Below are two pieces of code that basically perform the same task.
          > > Version A produces a segmentation fault, while version B works
          > > correctly. I understand why version B works correctly, but I do not
          > > understand why version A does not work.[/color]
          >
          > This is fully covered in the FAQ, as are the proper return values[/color]
          from[color=blue]
          > main (yours isn't one of them). Please check the FAQ before posting.[/color]
          [color=blue]
          > And learn to indent your code.[/color]

          Google Groups removes indentations from posts. My code was indented.
          [color=blue]
          > In the meantime, compare the following to your code:
          >
          > #include <stdio.h>
          > #include <stdlib.h>
          >
          > void init_arrayA(int **a, int num)
          > {
          > *a = malloc(num * sizeof **a);
          > }
          > int *init_arrayB(in t num)
          > {
          > int *a;
          > a = malloc(num * sizeof *a);
          > return a;
          > }
          >
          > int main()
          > {
          > int array_size = 5;
          > int *array;
          > init_arrayA(&ar ray, array_size);
          > if (!array)
          > fprintf(stderr, "malloc (A) failed\n");
          > else {
          > array[3] = 10;
          > printf("array[3] (A) = %d\n", array[3]);
          > free(array);
          > }
          > if (!(array = init_arrayB(arr ay_size)))
          > fprintf(stderr, "malloc (B) failed\n");
          > else {
          > array[3] = 12;
          > printf("array[3] (B) = %d\n", array[3]);
          > free(array);
          > }
          > return 0;
          > }
          >
          >
          > array[3] (A) = 10
          > array[3] (B) = 12
          >
          >[color=green]
          > > Can anyone elaborate? Thanks.[/color]
          >
          > We really shouldn't. Encouraging people to misbehave by posting
          > questions without checking the FAQ and following the newsgroup first[/color]
          is[color=blue]
          > a bad idea.[/color]

          "Misbehave? " Oh, please... Thank you for the help, but if you are going
          to be a jerk about it, I would rather you not respond. Besides, if my
          question had not been in the FAQ, I'm sure you would have labelled it
          as an obvious homework question, or something.
          If my posts unsettle you, I urge you to utilize your killfile.

          Comment

          • Flash Gordon

            #6
            Re: Pointer initialization question...

            On 27 Dec 2004 13:57:47 -0800
            "No Such Luck" <no_suchluck@ho tmail.com> wrote:
            [color=blue]
            > Martin Ambuhl wrote:[color=green]
            > > No Such Luck wrote:[color=darkred]
            > > > Hi all:
            > > >
            > > > Below are two pieces of code that basically perform the same task.
            > > > Version A produces a segmentation fault, while version B works
            > > > correctly. I understand why version B works correctly, but I do
            > > > not understand why version A does not work.[/color]
            > >
            > > This is fully covered in the FAQ, as are the proper return values
            > > from main (yours isn't one of them). Please check the FAQ before
            > > posting.[/color]
            >[color=green]
            > > And learn to indent your code.[/color]
            >
            > Google Groups removes indentations from posts. My code was indented.[/color]

            Then use a real news client with a real news server. If your ISP does
            not provide a news server then the people at http://news.individual.net/
            provide one for free. I'm sure I'm not the only one who tends to not
            bother reading code with no formatting.

            <snip>
            [color=blue][color=green][color=darkred]
            > > > Can anyone elaborate? Thanks.[/color]
            > >
            > > We really shouldn't. Encouraging people to misbehave by posting
            > > questions without checking the FAQ and following the newsgroup first
            > > is a bad idea.[/color]
            >
            > "Misbehave? " Oh, please... Thank you for the help, but if you are
            > going to be a jerk about it, I would rather you not respond. Besides,
            > if my question had not been in the FAQ, I'm sure you would have
            > labelled it as an obvious homework question, or something.[/color]

            It's in the pointers section of the FAQ, not unreasonable when the
            question is about initialising a pointer, and the question starts "I
            have a function which accepts, and is supposed to initialize, a
            pointer..." which would seem fairly obviously related to your problem.

            [color=blue]
            > If my posts unsettle you, I urge you to utilize your killfile.[/color]

            The problem for you is that if you get the people who can help you to
            killfile you then you will find yourself not getting any help.
            --
            Flash Gordon
            Living in interesting times.
            Although my email address says spam, it is real and I read it.

            Comment

            • E. Robert Tisdale

              #7
              Re: Pointer initialization question...

              No Such Luck wrote:
              [color=blue]
              > Martin Ambuhl wrote:
              >[color=green]
              >>Encouraging people to misbehave by posting questions
              >>without checking the FAQ and following the newsgroup first
              >>is a bad idea.[/color]
              >
              > "Misbehave? " Oh, please...
              > Thank you for the help, but if you are going to be a jerk about it,
              > I would rather you not respond.
              > Besides, if my question had not been in the FAQ, I'm sure [that]
              > you would have labelled it as an obvious homework question, or something.
              > If my posts unsettle you, I urge you to utilize your killfile.[/color]

              The comp.lang.c newsgroup has more than its share of indigenous trolls.
              You should learn to recognize them and ignore as soon as possible.

              Comment

              • Malcolm

                #8
                Re: Pointer initialization question...

                "E. Robert Tisdale" <E.Robert.Tisda le@jpl.nasa.gov > wrote[color=blue]
                >
                > The comp.lang.c newsgroup has more than its share of indigenous trolls.
                > You should learn to recognize them and ignore as soon as possible.
                >[/color]
                You seem to have a troll obsession. In fact we have many irritating posters,
                but few trolls, who are people who are deliberately trying to disrupt the
                ng.

                More importantly, most of us are adults and professional programmers. We
                really aren't interested in this subject.


                Comment

                • Barry Schwarz

                  #9
                  Re: Pointer initialization question...

                  On 27 Dec 2004 00:29:53 -0800, "No Such Luck"
                  <no_suchluck@ho tmail.com> wrote:
                  [color=blue]
                  >Hi all:
                  >
                  >Below are two pieces of code that basically perform the same task.
                  >Version A produces a segmentation fault, while version B works
                  >correctly. I understand why version B works correctly, but I do not
                  >understand why version A does not work. It seems to me that in Version
                  >A, a pointer to an array of integers is passed as a parameter to
                  >init_array, and whether that pointer is NULL or not, is should be
                  >initialized as a new array of integers.
                  >
                  >Can anyone elaborate? Thanks.
                  >
                  >---------Version A (Seg Fault)--------
                  >
                  >#include <stdio.h>
                  >#include <stdlib.h>
                  >
                  >void init_array (int * array, int num)
                  >{
                  >array = (int *)malloc(sizeof (int) * num);
                  >}
                  >
                  >int main ()
                  >{
                  >int array_size = 5;
                  >int * array;
                  >init_array(arr ay, array_size);[/color]

                  The variable array is passed to init_array by value. (Since it was
                  not initialized, this invokes undefined behavior which is a different
                  problem.) When init_array returns, the value of array in main is
                  still uninitialized.
                  [color=blue]
                  >array[3] = 10; /* This causes a segmentation fault */
                  >return 1;
                  >}
                  >
                  >---------Version B (Works Correctly)--------
                  >
                  >#include <stdio.h>
                  >#include <stdlib.h>
                  >
                  >int * init_array (int num)
                  >{
                  >int * array;
                  >array = (int *)malloc(sizeof (int) * num);[/color]

                  The cast is both unnecessary and undesirable.
                  [color=blue]
                  >return array;
                  >}
                  >
                  >int main ()
                  >{
                  >int array_size = 5;
                  >int * array;
                  >array = init_array(arra y_size);
                  > array[3] = 10;
                  > return 1;
                  >}[/color]



                  <<Remove the del for email>>

                  Comment

                  • dragoncoder

                    #10
                    Re: Pointer initialization question...

                    There is no array anywhere. A variable named array which has a type
                    int* is passed by value to the function. Where a local copy of it is
                    created and that local variable is malloced to some memory. Thats why
                    your original array does not gets malloced. What else, the allocated
                    memory inside the function init_array() is gone and there is no way you
                    can free it. you have a couple of options to do this thing. The
                    simplest one you have already showed as the version B. Another one is
                    as follows.

                    Pass the address of the pointer (int**) so that it can be modified
                    inside the function.

                    void init_array (int ** array, int num)
                    {
                    *array = (int *)malloc(sizeof (int) * num);
                    }

                    Ofcourse main should be changed for the call of function. Instead it
                    will be called like this now.
                    init_array(&arr ay, array_size);

                    Cheers.

                    Comment

                    • xarax

                      #11
                      Re: Pointer initialization question...

                      "dragoncode r" <pktiwary@gmail .com> wrote in message
                      news:1104206260 .300518.38910@z 14g2000cwz.goog legroups.com...[color=blue]
                      > There is no array anywhere. A variable named array which has a type
                      > int* is passed by value to the function. Where a local copy of it is
                      > created and that local variable is malloced to some memory. Thats why
                      > your original array does not gets malloced. What else, the allocated
                      > memory inside the function init_array() is gone and there is no way you
                      > can free it. you have a couple of options to do this thing. The
                      > simplest one you have already showed as the version B. Another one is
                      > as follows.
                      >
                      > Pass the address of the pointer (int**) so that it can be modified
                      > inside the function.
                      >[/color]

                      #include <stdlib.h>
                      [color=blue]
                      > void init_array (int ** array, int num)
                      > {
                      > *array = (int *)malloc(sizeof (int) * num);[/color]

                      *array = malloc(num * sizeof **array);

                      OR:

                      *array = calloc(num,size of **array);
                      [color=blue]
                      > }
                      >
                      > Ofcourse main should be changed for the call of function. Instead it
                      > will be called like this now.
                      > init_array(&arr ay, array_size);
                      >
                      > Cheers.
                      >[/color]


                      Comment

                      • No Such Luck

                        #12
                        Re: Pointer initialization question...


                        Flash Gordon wrote:[color=blue]
                        > On 27 Dec 2004 13:57:47 -0800
                        > "No Such Luck" <no_suchluck@ho tmail.com> wrote:
                        >[color=green]
                        > > Martin Ambuhl wrote:[color=darkred]
                        > > > No Such Luck wrote:
                        > > > > Hi all:
                        > > > >
                        > > > > Below are two pieces of code that basically perform the same[/color][/color][/color]
                        task.[color=blue][color=green][color=darkred]
                        > > > > Version A produces a segmentation fault, while version B works
                        > > > > correctly. I understand why version B works correctly, but I do
                        > > > > not understand why version A does not work.
                        > > >
                        > > > This is fully covered in the FAQ, as are the proper return values
                        > > > from main (yours isn't one of them). Please check the FAQ before
                        > > > posting.[/color]
                        > >[color=darkred]
                        > > > And learn to indent your code.[/color]
                        > >
                        > > Google Groups removes indentations from posts. My code was[/color][/color]
                        indented.[color=blue]
                        >
                        > Then use a real news client with a real news server. If your ISP does
                        > not provide a news server then the people at[/color]
                        http://news.individual.net/[color=blue]
                        > provide one for free. I'm sure I'm not the only one who tends to not
                        > bother reading code with no formatting.[/color]

                        I do have a real news server. It's hard to access cross country when
                        I'm visiting family for the holidays. Thanks for the alternative,
                        though.
                        [color=blue]
                        > <snip>
                        >[color=green][color=darkred]
                        > > > > Can anyone elaborate? Thanks.
                        > > >
                        > > > We really shouldn't. Encouraging people to misbehave by posting
                        > > > questions without checking the FAQ and following the newsgroup[/color][/color][/color]
                        first[color=blue][color=green][color=darkred]
                        > > > is a bad idea.[/color]
                        > >
                        > > "Misbehave? " Oh, please... Thank you for the help, but if you are
                        > > going to be a jerk about it, I would rather you not respond.[/color][/color]
                        Besides,[color=blue][color=green]
                        > > if my question had not been in the FAQ, I'm sure you would have
                        > > labelled it as an obvious homework question, or something.[/color]
                        >
                        > It's in the pointers section of the FAQ, not unreasonable when the
                        > question is about initialising a pointer, and the question starts "I
                        > have a function which accepts, and is supposed to initialize, a
                        > pointer..." which would seem fairly obviously related to your[/color]
                        problem.[color=blue]
                        > http://www.eskimo.com/~scs/C-faq/q4.8.html
                        >[color=green]
                        > > If my posts unsettle you, I urge you to utilize your killfile.[/color]
                        >
                        > The problem for you is that if you get the people who can help you to
                        > killfile you then you will find yourself not getting any help.[/color]

                        No, the problem for you is that if half the people here help others
                        unconditionally , and the other half bitches about "not reading the FAQ"
                        and "asking obvious homework questions" and eventually killfiles me,
                        I'll still get a bunch of help.

                        Comment

                        • Keith Thompson

                          #13
                          Re: Pointer initialization question...

                          "No Such Luck" <no_suchluck@ho tmail.com> writes:
                          [...][color=blue]
                          > No, the problem for you is that if half the people here help others
                          > unconditionally , and the other half bitches about "not reading the FAQ"
                          > and "asking obvious homework questions" and eventually killfiles me,
                          > I'll still get a bunch of help.[/color]

                          The problem is that if enough people "help others unconditionally ",
                          this will become known as the place to go to get unconditional help on
                          any topic, whether it's related to C or not. The quality of such help
                          will be limited because most of us don't have enough expertise on
                          whatever the question was about to be able to correct errors, and
                          actual discussions of the C programming language as defined by the
                          ANSI/ISO standards will be lost in the noise.

                          I understand that this actually happened to comp.lang.c++; it took
                          that newsgroup several years to recover and become useful again.

                          --
                          Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                          San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                          We must do something. This is something. Therefore, we must do this.

                          Comment

                          • No Such Luck

                            #14
                            Re: Pointer initialization question...


                            Keith Thompson wrote:[color=blue]
                            > "No Such Luck" <no_suchluck@ho tmail.com> writes:
                            > [...][color=green]
                            > > No, the problem for you is that if half the people here help others
                            > > unconditionally , and the other half bitches about "not reading the[/color][/color]
                            FAQ"[color=blue][color=green]
                            > > and "asking obvious homework questions" and eventually killfiles[/color][/color]
                            me,[color=blue][color=green]
                            > > I'll still get a bunch of help.[/color]
                            >
                            > The problem is that if enough people "help others unconditionally ",
                            > this will become known as the place to go to get unconditional help[/color]
                            on[color=blue]
                            > any topic, whether it's related to C or not.[/color]

                            I agree with you that the specific focus of this group (and other
                            groups, for that matter) should be strictly enforced, but I think
                            you're stretching things a bit. I asked a legitimate C programming
                            language question. It's not like I asked a question regarding math or
                            sports trivia.

                            If you feel I have asked a question already answered in the FAQ, or
                            feel I am trying to have my homework done for me, or are uninterested
                            in trying to decipher unindented code, or turn to stone at the sight of
                            incorrect return values for main... Simply, don't respond. And if my
                            posts continue to annoy you, update your killfile.

                            Comment

                            • Old Wolf

                              #15
                              Re: Pointer initialization question...

                              xarax wrote:[color=blue]
                              > "dragoncode r" <pktiwary@gmail .com> wrote in message[color=green]
                              > > void init_array (int ** array, int num)
                              > > {
                              > > *array = (int *)malloc(sizeof (int) * num);[/color]
                              >
                              > *array = malloc(num * sizeof **array);
                              > OR:
                              > *array = calloc(num,size of **array);[color=green]
                              > > }[/color][/color]

                              calloc does not generate null pointers. So it is
                              slower than the malloc version as well as maybe
                              lulling you into a false sense of security, if it
                              does generate null pointers on your platform.
                              So the malloc version is to be preferred.

                              Comment

                              Working...