c++ - c-用这种方式设计一个基本链表遇到的一个问题?

浏览:43日期:2023-03-28

问题描述

(非学校作业, 我是非 cs 相关的学生)

遇到的问题是 有些 next 指向的空间本应该是 NULL, 但是 debug 时提示 next 是error = read memory from..., 想问下这里为什么会这样呢 (clang 环境下有一定几率出现这个 error 提示, 有时候能正确输出), 应该怎么改正呢? 谢谢大家(其实我也想了很久了, 但是一直想不通.

/** @file log.c */#include <stdlib.h>#include <string.h>#include <stdio.h>typedef struct _node{ char* cmd; struct _node* next;}node;typedef struct _log_t { node* head;} log_t;void log_init(log_t *l);void log_destroy(log_t* l);void log_push(log_t* l, const char *item);char *log_search(log_t* l, const char *prefix);/**对log进行初始化,log的“构造函数” */void log_init(log_t *l) { l->head = NULL;}/**销毁一个log,释放所有内存空间,log的“析构函数” */void log_destroy(log_t* l) { if (l->head == NULL) {return; } node *current_node = l->head; while (current_node != NULL) {node *delete_node = current_node;current_node = current_node->next;free(delete_node); } l->head = NULL;}/**向log中推入一个字符串,你可以将log视为一个由链表组成的栈 */void log_push(log_t* l, const char *item) { if (l->head == NULL) {node *new_head = (node*)malloc(sizeof(node));l->head = new_head;l->head->cmd = item;return; } node *current_node = l->head; while (current_node->next != NULL) //第一处 next 出错点 {current_node = current_node->next; } node *new_node = (node*)malloc(sizeof(node)); new_node->cmd = item; current_node->next = new_node;}/**搜索log中是否含有对应前缀的字符串 */char *log_search(log_t* l, const char *prefix) { node *current_node = (node*)malloc(sizeof(node)); current_node = l->head; while (current_node != NULL) {if (current_node->cmd == prefix) //第二处 next 出错点{ return current_node->cmd;}current_node = current_node->next; } return NULL;}int main(){ log_t *linkedlist = (log_t*)malloc(sizeof(log_t)); log_init(linkedlist); log_push(linkedlist, 'I love you'); log_push(linkedlist, 'Me too'); printf('%sn', log_search(linkedlist, 'I love you')); printf('%sn', log_search(linkedlist, 'Me too')); printf('%s', log_search(linkedlist, 'hhh')); log_destroy(linkedlist);}

问题解答

回答1:

刚刚才想到, next 指向 NULL 就可以解决了-_-||

相关文章: