malloc problem

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

    #1

    malloc problem

    Hello everyone:
    I have a problem like this :
    typedef struct node {
    char *data;
    struct node *next;
    }lnode;
    when I allocate space for node p : p = (lnode *)malloc(sizeof (struct
    node));
    it happened display : Segmentation fault.
    I think it will be problem the 'char *data' is not enough
    initialization and compiler
    cann't know the size precisely. so the space allocated is not satisfy
    with the input data ??
    so what i should do for this ?

  • hari4063

    #2
    Re: malloc problem

    It will be better to provide little source code. but I think that You do
    not allocate memory for string. So, after creating new node with malloc (p
    = (lnode *)malloc(sizeof (structnode));) You must allocate p->data:

    p->data = (char*)malloc(s trlen(str)+1);
    strcpy(p->data, str);

    Best,
    Zaharije Pasalic



    Comment

    • Guillaume

      #3
      Re: malloc problem

      Hi, do you believe in spontaneous generation?

      It looks like you do. ;-)

      Comment

      • Nitin

        #4
        Re: malloc problem

        Verify whether stdlib.h is included.Non inclusion of this may result in
        segmentation fault whenever malloc is called on some flavours of unix

        Comment

        • Thomas Matthews

          #5
          Re: malloc problem

          sabads wrote:
          [color=blue]
          > Hello everyone:
          > I have a problem like this :
          > typedef struct node {
          > char *data;
          > struct node *next;
          > }lnode;
          > when I allocate space for node p : p = (lnode *)malloc(sizeof (struct
          > node));
          > it happened display : Segmentation fault.
          > I think it will be problem the 'char *data' is not enough
          > initialization and compiler
          > cann't know the size precisely. so the space allocated is not satisfy
          > with the input data ??
          > so what i should do for this ?
          >[/color]

          First off, include the stdlib.h header file, that way
          you don't need to cast the result of malloc:
          #include <stdlib.h>

          To allocate a node structure:
          struct node * Allocate_Node()
          {
          struct node * new_node;
          new_node = malloc(sizeof(s truct node));
          if (new_node)
          {
          new_node->data = 0;
          new_node->next = 0;
          }
          return new_node;
          }


          To allocate characters, during run-time, for the
          data field of the node:
          struct node * new_node;

          new_node = Allocate_Node() ;
          if (new_node)
          {
          new_node->data = malloc(/* number of characters + 1 */);
          }


          --
          Thomas Matthews

          C++ newsgroup welcome message:

          C++ Faq: http://www.parashift.com/c++-faq-lite
          C Faq: http://www.eskimo.com/~scs/c-faq/top.html
          alt.comp.lang.l earn.c-c++ faq:

          Other sites:
          http://www.josuttis.com -- C++ STL Library book
          http://www.sgi.com/tech/stl -- Standard Template Library

          Comment

          • sabads

            #6
            Re: malloc problem

            Thank all of your reples !
            ////////////////////////////////////
            #include <stdio.h>
            #include <stdlib.h>
            #include <string.h>

            typedef struct node {
            char *data;
            struct node *next;
            }lnode;

            int main()
            {
            int i = 0;
            lnode *p,*head = NULL;
            char *str;

            printf("input string: \n");
            for (i = 1; i < 5; i++) {
            scanf("%s",str) ;
            p = (lnode *)malloc(sizeof (lnode));
            p->data = (char *)malloc(strlen (str)+1);
            strcpy(p->data,str);
            p->next = head;
            head = p;
            }
            p = head;
            while (p != NULL) {
            printf("%s ",p->data);
            p = p->next;
            }
            return 0;
            }
            this is my test code but still Segmentation fault. i don't know what's
            wrong ?

            Comment

            • pari

              #7
              Re: malloc problem

              str does not point to any allocated space.
              sabads wrote:[color=blue]
              > Thank all of your reples !
              > ////////////////////////////////////
              > #include <stdio.h>
              > #include <stdlib.h>
              > #include <string.h>
              >
              > typedef struct node {
              > char *data;
              > struct node *next;
              > }lnode;
              >
              > int main()
              > {
              > int i = 0;
              > lnode *p,*head = NULL;
              > char *str;
              >
              > printf("input string: \n");
              > for (i = 1; i < 5; i++) {
              > scanf("%s",str) ;
              > p = (lnode *)malloc(sizeof (lnode));
              > p->data = (char *)malloc(strlen (str)+1);
              > strcpy(p->data,str);
              > p->next = head;
              > head = p;
              > }
              > p = head;
              > while (p != NULL) {
              > printf("%s ",p->data);
              > p = p->next;
              > }
              > return 0;
              > }
              > this is my test code but still Segmentation fault. i don't know[/color]
              what's[color=blue]
              > wrong ?[/color]

              Comment

              • David Resnick

                #8
                Re: malloc problem

                sabads wrote:[color=blue]
                > Thank all of your reples !
                > ////////////////////////////////////
                > #include <stdio.h>
                > #include <stdlib.h>
                > #include <string.h>
                >
                > typedef struct node {
                > char *data;
                > struct node *next;
                > }lnode;
                >
                > int main()
                > {
                > int i = 0;
                > lnode *p,*head = NULL;
                > char *str;
                >
                > printf("input string: \n");
                > for (i = 1; i < 5; i++) {
                > scanf("%s",str) ;[/color]

                str is an uninitialized pointer. It likely doesn't point to somewhere
                you can write. This should be easy to debug, you should become
                comfortable using whatever tools you have available to help identify
                such things (e.g. on linux using gdb to step through code /examine core
                or valgrind). You could repair this by declaring char
                str[MAX_LINE_LENGTH]; and by telling scanf not to read more than
                MAX_LINE_LENGTH characters into it.

                -David

                Comment

                • Al Bowers

                  #9
                  Re: malloc problem



                  sabads wrote:[color=blue]
                  > Thank all of your reples !
                  > ////////////////////////////////////
                  > #include <stdio.h>
                  > #include <stdlib.h>
                  > #include <string.h>
                  >
                  > typedef struct node {
                  > char *data;
                  > struct node *next;
                  > }lnode;
                  >
                  > int main()
                  > {
                  > int i = 0;
                  > lnode *p,*head = NULL;
                  > char *str;
                  >
                  > printf("input string: \n");
                  > for (i = 1; i < 5; i++) {
                  > scanf("%s",str) ;
                  > p = (lnode *)malloc(sizeof (lnode));
                  > p->data = (char *)malloc(strlen (str)+1);
                  > strcpy(p->data,str);
                  > p->next = head;
                  > head = p;
                  > }
                  > p = head;
                  > while (p != NULL) {
                  > printf("%s ",p->data);
                  > p = p->next;
                  > }
                  > return 0;
                  > }
                  > this is my test code but still Segmentation fault. i don't know what's
                  > wrong ?
                  >[/color]

                  You are attempting to input the string data into a char *str
                  which has no space allocated for it. You will need to first
                  allocate storage for the data and then get the data. You
                  could write a function that does this, see function fgetline
                  below.

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

                  typedef struct node {
                  char *data;
                  struct node *next;
                  }lnode;

                  int AddNode(lnode **head, const char *data);
                  char *fgetline(FILE *fp);
                  void PrintNodes(lnod e *head);
                  void FreeNodes(lnode **head);

                  int main(void)
                  {
                  int i = 0;
                  lnode *head = NULL;
                  char *str;

                  for (i = 0; i < 5; i++)
                  {
                  printf("Input String #%d: ",i+1);
                  fflush(stdout);
                  str = fgetline(stdin) ;
                  if(str != NULL) AddNode(&head,s tr);
                  }
                  puts("\n\tThe Node data is:");
                  PrintNodes(head );
                  FreeNodes(&head );
                  return 0;
                  }

                  char *fgetline(FILE *fp)
                  {
                  char *s, *tmp;
                  const size_t BLOCK = 32;
                  size_t count;
                  int ch;

                  for(count = 0, s = NULL;
                  (ch = fgetc(fp)) != EOF && ch != '\n';count++)
                  {
                  if(count%BLOCK == 0)
                  {
                  tmp = realloc(s,count +BLOCK+1);
                  if(tmp == NULL)
                  {
                  free(s);
                  return NULL;
                  }
                  s = tmp;
                  }
                  s[count] = ch;
                  }
                  if(s) s[count] = '\0';
                  return s;
                  }

                  int AddNode(lnode **head, const char *data)
                  {
                  lnode *tmp;

                  if((tmp = malloc(sizeof *tmp)) == NULL)
                  return 0;
                  tmp->data = (char *)data;
                  tmp->next = *head;
                  *head = tmp;
                  return 1;
                  }

                  void PrintNodes(lnod e *head)
                  {
                  for( ; head; head = head->next)
                  puts(head->data);
                  return;
                  }

                  void FreeNodes(lnode **head)
                  {
                  lnode *tmp;

                  for( ; *head; *head = tmp)
                  {
                  tmp = (*head)->next;
                  free((*head)->data);
                  free(*head);
                  }
                  return;
                  }

                  --
                  Al Bowers
                  Tampa, Fl USA
                  mailto: xabowers@myrapi dsys.com (remove the x to send email)
                  Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!


                  Comment

                  • Martin Ambuhl

                    #10
                    Re: malloc problem

                    sabads wrote:
                    [color=blue]
                    > int main()
                    > {
                    > int i = 0;
                    > lnode *p,*head = NULL;
                    > char *str;
                    >
                    > printf("input string: \n");
                    > for (i = 1; i < 5; i++) {
                    > scanf("%s",str) ;[/color]

                    This is the segmentation fault. 'str' points to your toaster, which is
                    a read-only device.

                    Comment

                    • sabads

                      #11
                      Re: malloc problem

                      Thank you all of you ,
                      especially Al Bowers, thank you.I learn a lot.

                      Comment

                      • Michael Wojcik

                        #12
                        Re: malloc problem


                        In article <1112108287.592 649.75320@g14g2 000cwa.googlegr oups.com>, "sabads" <sabads@163.com > writes:

                        Various people have noted your major error (writing through an
                        uninitialized pointer), but it's worth pointing out some minor
                        ones and style issues:
                        [color=blue]
                        > int main()[/color]

                        This should be one of:

                        int main(void)
                        int main(int argc, char **argv)

                        (the parameter names in the second form are unimportant) for a
                        program running under a hosted implementation.
                        [color=blue]
                        > printf("input string: \n");[/color]

                        The space before the newline is probably not useful, and many
                        people prefer puts (or fputs) to printf (and fprintf) if no
                        formatting is being done. Note that puts adds a newline
                        automatically, so in this case you'd have:

                        puts("input string:");

                        Use fputs if you don't want a newline.
                        [color=blue]
                        > p = (lnode *)malloc(sizeof (lnode));[/color]

                        Unless you're writing C++, the cast is unnecessary and can
                        conceal the error of forgetting to include stdlib.h. If you
                        use sizeof on the dereferenced pointer rather than a type
                        name, then you avoid a possible error if the type of the
                        object pointed to by p changes. Thus:

                        p = malloc(sizeof *p);

                        Note this is also more concise and easier to read.

                        You've neglected to check if malloc succeeded. Even in little
                        test programs I believe in making that check; prototype code
                        has a way of getting into production code.

                        If you write a skeleton test program for prototyping, and
                        include in it a function that, say, displays a message and
                        calls "exit(EXIT_FAIL URE)", then you can use that if a malloc
                        fails with minimal effort on your part.
                        [color=blue]
                        > p->data = (char *)malloc(strlen (str)+1);[/color]

                        Similarly here:

                        p->data = malloc(strlen(s tr)+1);
                        if (! p->data) ...

                        --
                        Michael Wojcik michael.wojcik@ microfocus.com

                        But I still wouldn't count out the monkey - modern novelists being as
                        unpredictable as they are at times. -- Marilyn J. Miller

                        Comment

                        • Michael Wojcik

                          #13
                          Re: malloc problem


                          In article <424b9c99.65304 502@news.indivi dual.net>, rlb@hoekstra-uitgeverij.nl (Richard Bos) writes:[color=blue]
                          > mwojcik@newsguy .com (Michael Wojcik) wrote:[color=green]
                          > > In article <1112108287.592 649.75320@g14g2 000cwa.googlegr oups.com>, "sabads" <sabads@163.com > writes:
                          > >[color=darkred]
                          > > > int main()[/color]
                          > >
                          > > This should be one of:
                          > >
                          > > int main(void)
                          > > int main(int argc, char **argv)[/color]
                          >
                          > Actually, it needn't. It's better style, but neither C89 nor C99
                          > requires the void or parameters. (C99 requires the explicit int, though,
                          > which C89 did not.)[/color]

                          That's not how I read 9899-1990 5.1.2.2.1:

                          [main] can be defined with no parameters:

                          int main(void) { /*...*/ }

                          or with two parameters...

                          6.7.1 certainly makes the parameter list optional in general, but
                          ISTM that a conforming implementation could require one of the two
                          forms for main described in 5.1.2.2.1. I don't see anything that
                          requires an implementation to accept "int main()". Thus "int main()"
                          is non-portable (which is what I meant by "should be" above).

                          But I'm prepared to be enlightened.

                          --
                          Michael Wojcik michael.wojcik@ microfocus.com

                          I would never understand our engineer. But is there anything in this world
                          that *isn't* made out of words? -- Tawada Yoko (trans. Margaret Mitsutani)

                          Comment

                          • Mark McIntyre

                            #14
                            Re: malloc problem

                            On 31 Mar 2005 18:04:52 GMT, in comp.lang.c , mwojcik@newsguy .com
                            (Michael Wojcik) wrote:
                            [color=blue]
                            >That's not how I read 9899-1990 5.1.2.2.1:
                            >
                            > int main(void) { /*...*/ }[/color]

                            this is totally equivalent to
                            int main() {/*...*/}

                            in a function definition.
                            [color=blue]
                            >6.7.1 certainly makes the parameter list optional in general, but
                            >ISTM that a conforming implementation could require one of the two
                            >forms for main described in 5.1.2.2.1. I don't see anything that
                            >requires an implementation to accept "int main()".[/color]

                            The grammar of the language requires it.

                            --
                            Mark McIntyre
                            CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
                            CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

                            Comment

                            • Keith Thompson

                              #15
                              Re: malloc problem

                              Mark McIntyre <markmcintyre@s pamcop.net> writes:[color=blue]
                              > On 31 Mar 2005 18:04:52 GMT, in comp.lang.c , mwojcik@newsguy .com
                              > (Michael Wojcik) wrote:
                              >[color=green]
                              >>That's not how I read 9899-1990 5.1.2.2.1:
                              >>
                              >> int main(void) { /*...*/ }[/color]
                              >
                              > this is totally equivalent to
                              > int main() {/*...*/}
                              >
                              > in a function definition.[/color]

                              I think you're right. C99 6.7.5.3p14 says:

                              [...] An empty list in a function declarator that is part of a
                              definition of that function specifies that the function has no
                              parameters. The empty list in a function declarator that is not
                              part of a definition of that function specifies that no
                              information about the number or types of the parameters is
                              supplied.

                              I had been thinking that int main() would allow mismatched arguments
                              on a recursive call to main, but the above shows that I was mistaken.
                              I just tried a test case on several compilers, and most of them appear
                              to get this wrong as well, issuing no diagnostics for the following:

                              #include <stdio.h>

                              void foo()
                              {
                              printf("In foo\n");
                              }

                              int main()
                              {
                              foo();
                              foo(42);
                              return 0;
                              }

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

                              Working...