我很困惑我需要在哪里使用 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);
}
在表达式
shallow = shallow->next
中,shallow->next
没有被初始化。这导致 UB.
在
sl_shallow_copy()
你分配一个slist
但然后在循环中你尝试复制一些任意数量的节点。您需要在该循环中分配新节点。
如果
malloc()
失败(尽管不太可能),您的程序将由于 NULL 取消引用而出现段错误。
sl_cons()
:如果您传递常规字符串文字,当您尝试释放只读字符串时,它将发生段错误。如果你想释放字符串,那么你可能想要复制它。
在
sl_free()
中,您递归地释放节点。在 C 中,想要更喜欢迭代方法以避免在节点太多时炸毁堆栈。
sl_free()
:如果你释放原始和浅克隆,字符串将被释放两次,这是 UB.