Seg Fault in Knowledge Tree

后端 未结 3 353
北荒
北荒 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
       }
      

提交回复
热议问题