Seg Fault in Knowledge Tree

后端 未结 3 354
北荒
北荒 2021-01-28 13:16

I am implementing a knowledge tree in c that can read from a file. I am getting a seg fault in my newStr function. I\'m not able to test the rest of my code with this problem. I

相关标签:
3条回答
  • 2021-01-28 13:45

    There might be several more, but here's some points on what's wrong:

    1. Your newStr function is just very, very wrong. At a guess you'd want something like:

      char * newStr (char * charBuffer)
      {
        char *newStr;
        if(charBuffer[0] == 'A' || charBuffer[0] == 'Q') {
          newStr = strdup(&charBuffer[1]);
        } else {
          newStr = strdup("");
        }
        if(newStr == NULL) {
            //handle error
        }
        return newStr;
      }
      
    2. You can't cast a string to a char like you do here:

       if(ans[0] == (char)"Y" || ans[0] == (char)"y")
      

      Do instead(same for similar code elsewhere too)

       if(ans[0] =='Y' || ans[0] == 'y')
      
    3. Same as above when you call putc, don't do

       fputc((char)"A", f);
      

      Do

       fputc('A', f);
      
    4. scanf needs a format string, don't do:

      scanf(ans);
      

      Do e.g. (or just use fgets again)

      if(scanf("%99s",ans) != 1) {
         //handle error
       }
      
    0 讨论(0)
  • 2021-01-28 13:46

    "+" operator as string concatenation does not work in c.

    If you actually want to copy the a string use strdup(). This function allocates memory and copies the string into it.

    Don't forget to free the allocated memory when done using it.

    0 讨论(0)
  • 2021-01-28 13:53
    char * newStr (char * charBuffer)
    {
      int i;
      int length = strlen(charBuffer);
      char newStr;
      if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
        for(i=1; i<length; i++)
            newStr += charBuffer[i]; 
      }
      return (newStr + "\0");
    }
    

    Well, there's a few interesting things here... To get down to brass tacks, you're trying to copy the contents of a character pointer into another and this function isn't going to do that. All you're really doing is summing the value of each char in charBuffer into newStr because a char is really just an 8-bit integer and then you return that integer as a pointer through an implicit cast so it is now being treated as a memory address.

    You should look to use strdup(), as has been noted, since this is exactly what the function is supposed to do. No need to reinvent the wheel. :)

    0 讨论(0)
提交回复
热议问题