为什么使用此递归函数会出现分段错误?

问题描述 投票:0回答:1
void displayAllTVShowsOfActor(TVShow* root, string actor) {
    string *a = root->actor;
    if (root != NULL) {
        while (*a != "NULL") {
          if (*a == actor)
          {
            cout << root->name << endl; 
          }
          cout << "here";
          a = (a+1); 
        }
        displayAllTVShowsOfActor(root->left, actor);
        displayAllTVShowsOfActor(root->right, actor);
    }
   } 
 void displayAllTVShowsOfActor(TVShow* root, string actor) {
    string *a;
    if (root != NULL) {
       a = root->actor;
        while (*a != "NULL") {
          if (*a == actor)
          {
            cout << root->name << endl; 
          }
          cout << "here";
          a = (a+1); 
        }
        displayAllTVShowsOfActor(root->left, actor);
        displayAllTVShowsOfActor(root->right, actor);
    }
   }

第一个导致分段错误,但如果我将第一行移动到 if 语句之后,就像我在第二个中所做的那样,它会起作用。是什么导致了分段错误?

segmentation-fault
1个回答
0
投票

在第一个代码中,它似乎抛出段错误,因为根可能为空。

在 C 中,取消引用空指针是未定义的行为

相关:解引用空指针

© www.soinside.com 2019 - 2024. All rights reserved.