Seg Fault in Knowledge Tree

后端 未结 3 368
北荒
北荒 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:53

    char * newStr (char * charBuffer)
    {
      int i;
      int length = strlen(charBuffer);
      char newStr;
      if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
        for(i=1; i

    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. :)

提交回复
热议问题