【问题标题】:I keep getting a segmentation fault and I can't find it! I think ive narrowed it down to a particular function我不断收到分段错误,但我找不到它!我想我把它缩小到一个特定的功能
【发布时间】:2021-11-09 05:39:15
【问题描述】:

我说它一定是这个函数,因为它在我输入一个 int 后立即停止并且它不读取 print 语句。

recipe** readAllRecipes(int numRecipes)
 {
   recipe** theRecipes = malloc(sizeof(recipe *) * numRecipes);
   int i;

   for(i = 0; i < numRecipes; i++)
   {
    scanf("%d", &theRecipes[i]->numItems);
    
    printf("\n\n\t\t here in readAll for loop\n");
    
    theRecipes[i] = readRecipe(theRecipes[i]->numItems);
   }

   return theRecipes;
}

【问题讨论】:

  • &amp;theRecipes[i]-&gt;numItems 那是访问无效内存。 theRecipes 已分配一些内存,但未分配单个 theRecipes[i] 条目。
  • @kaylum 哦,好吧,我需要在 for 循环中为theRecipes[i]-&gt;numItemstheRecipes[i] 分配内存... idk 我只是认为malloc(sizeof(recipe *) * numRecipes) 就足够了。我不太明白:c
  • 可能是scanf调用的第二个参数中的操作顺序,加括号试试。

标签: c pointers struct segmentation-fault dynamic-memory-allocation


【解决方案1】:

问题来了:

        scanf("%d", &theRecipes[i]->numItems);

theRecipise[i] 未初始化,您取消引用它。应该先分配:

        theRecipes[i] = malloc(sizeof(recipe));
        scanf("%d", &theRecipes[i]->numItems);

但我对此感到困惑:

    theRecipes[i] = readRecipe(theRecipes[i]->numItems);

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2015-01-14
    • 2018-01-19
    • 2020-05-28
    相关资源
    最近更新 更多