【问题标题】:Segmentation Fault when adding value into dynamic array将值添加到动态数组时出现分段错误
【发布时间】:2021-12-28 16:26:59
【问题描述】:

我想将值添加到我的.数组

typedef struct teleporter {
    int start;
    int end;
}teleporters;



int main(int argc, char **argv) {
    int lenght = 2;
    teleporters *teleportPlaces;
    teleporters mytele;
    mytele.start = 0;
    mytele.end = 0;
    teleportPlaces = calloc(2, sizeof(teleporters));//malloc (sizeof(teleporters) * (lenght));
    if (teleportPlaces != NULL) {
        teleportPlaces = NULL;
    }
    for (int i = 0; i < lenght; i++) {
        teleportPlaces[i] = mytele;
    }

    printf("Teleport END[0] = %d",teleportPlaces[0].end);
    free(teleportPlaces);
    return 0;
}

但每次我添加它时,都会出现分段错误,

我该如何解决这个错误?如果有关于它的文章或答案,那就太好了,谢谢

【问题讨论】:

  • calloc(2, sizeof(teleporters)*lenght);
  • if (teleportPlaces != NULL) { teleportPlaces = NULL; } - 这是什么?
  • @kofemann 2 是长度。
  • 呵呵if (teleportPlaces != NULL) {
  • 请解释一下你对calloc和printf之间所有行的理解。他们真的需要一些解释。或者,如果您通过显式代码保证为 NULL 的指针访问,请解释为什么您对段错误感到惊讶。

标签: c for-loop if-statement dynamic-memory-allocation null-pointer


【解决方案1】:

问题在于,您实际上是在分配地址后立即将其丢弃到您的 TeleportPlaces 中。

删除将 TeleportPlaces 指向 NULL 的 if 语句。

在 for 循环中,地址 teleportPlaces[i] 应该是数组开头的地址 (teleportPlaces) 和偏移量 (i)。但是,当您将其重新分配为指向 NULL 时,数组的实际地址会丢失,从而导致内存泄漏(因为如果您不知道地址,就无法释放 calloc)。

【讨论】:

    【解决方案2】:

    这个 if 语句

    if (teleportPlaces != NULL) {
        teleportPlaces = NULL;
    }
    

    没有意义。这意味着如果内存分配成功,您将指向分配内存的指针teleportPlaces 设置为NULL,从而产生内存泄漏。

    之后,您将在以下 for 循环中使用此空指针。

    删除此 if 语句或例如 write

    if (teleportPlaces == NULL) return 0;
    

    或者

    if (teleportPlaces != NULL) {
        for (int i = 0; i < lenght; i++) {
            teleportPlaces[i] = mytele;
        }
    
        printf("Teleport END[0] = %d\n",teleportPlaces[0].end);
    }
    
    free( teleportPlaces ); 
    

    你也可以简化这段代码sn-p

    teleporters mytele;
    mytele.start = 0;
    mytele.end = 0;
    

    以下方式

    teleporters mytele = { .start = 0, .end = 0 };
    

    也不要使用像2 这样的幻数。而不是这种说法

    teleportPlaces = calloc(2, sizeof(teleporters));
    

    你应该写

    teleportPlaces = calloc( length, sizeof(teleporters));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 2011-07-28
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多