如何在此代码中正确使用 malloc 以避免崩溃?

问题描述 投票:0回答:1

我很困惑我需要在哪里使用 malloc,它一直在崩溃。我不确定导航到下一个列表时是否需要重新分配内存。

struct string_list {
    char *s;
    struct string_list *next;
};

typedef struct string_list list;

slist *sl_cons(char *s, slist *strings){
    slist *result = (slist*)malloc(sizeof(slist));
    result -> s = s;
    result -> next = strings;
    return result;
}

slist *sl_shallow_copy(slist *strings){
    slist *shallow = (slist*)malloc(sizeof(slist));
    while(strings != NULL){
        shallow->s = strings->s;
        shallow = shallow->next;
        strings = strings->next;
    }
    return shallow;
}

void sl_free(slist *strings){
    if(strings != NULL){
        sl_free(strings->next);
        free(strings->s);
        free(strings);
    }
c string memory crash malloc
1个回答
1
投票
  1. 在表达式

    shallow = shallow->next
    中,
    shallow->next
    没有被初始化。这导致 UB.

  2. sl_shallow_copy()
    你分配一个
    slist
    但然后在循环中你尝试复制一些任意数量的节点。您需要在该循环中分配新节点。

  3. 如果

    malloc()
    失败(尽管不太可能),您的程序将由于 NULL 取消引用而出现段错误。

  4. sl_cons()
    :如果您传递常规字符串文字,当您尝试释放只读字符串时,它将发生段错误。如果你想释放字符串,那么你可能想要复制它。

  5. sl_free()
    中,您递归地释放节点。在 C 中,想要更喜欢迭代方法以避免在节点太多时炸毁堆栈。

  6. sl_free()
    :如果你释放原始和浅克隆,字符串将被释放两次,这是 UB.

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