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

查看:92
本文介绍了c++ - c-用这种方式设计一个基本链表遇到的一个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

(非学校作业, 我是非 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("%s\n", log_search(linkedlist, "I love you"));
    printf("%s\n", log_search(linkedlist, "Me too"));
    printf("%s", log_search(linkedlist, "hhh"));
    log_destroy(linkedlist);
}

解决方案

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

这篇关于c++ - c-用这种方式设计一个基本链表遇到的一个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆