【问题标题】:Segmentation fault: 11 when trying to modify struct分段错误:尝试修改结构时出现 11
【发布时间】:2012-03-13 03:04:53
【问题描述】:

我正在尝试将我的 char* 参数存储到结构指针的数据成员中。但是当我尝试这样做时,我收到了 Segmentation Fault: 11。

void macro_set(char *name, char *body)
{
    verify(body != NULL, "null arg body");

    bool  nameExists = false;

    if(macro_list.name == NULL)
    {
        macro_list.name = Strdup(name);
        macro_list.body = Strdup(body);
    }
    else
    {
        struct macro *current = &macro_list;

        for(; current != NULL; current = current->next)
        {

          if(strcmp(name, current->name) == 0)
          {
              current->body = Strdup(body);
              nameExists = true;
          }
        }

        if(!nameExists)
        {
            current->name = Strdup(name);           
        } 
    } 
}

当我尝试将名称存储到 current->name 时发生错误。感谢任何可以提供帮助的人!

【问题讨论】:

  • Strdup 不应大写!
  • Strdup 是我程序中的一个宏,因为我需要一些额外的功能。
  • macro_list 已在我的代码的另一部分中分配到内存中

标签: c segmentation-fault systems-programming


【解决方案1】:

如果没有一个macro_list 元素与name 匹配,则for 循环将以

nameExists = false
current = NULL 退出。

那么后面的if就会为真,行

current->name = Strdup(name);

有效分配

((struct macro *) NULL)->name = Strdup(name);

【讨论】:

    猜你喜欢
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 2012-04-30
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多