结构体指针内值无法更新,所有节点均存储最后一条日志值求助
问题原因与解决方案
问题根源
你在main中定义的timestamp、logLevel、message是栈上的固定内存区域,每次循环输入都会覆盖这些区域的内容。而insertLoglogfile函数里直接将这些数组的指针赋值给链表节点的成员,导致所有节点的字符串指针都指向同一块内存。当最后一次输入覆盖数组后,所有节点自然显示最后一条日志的内容。
修复后的代码
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct logfile { char *timestamp; char *logLevel; char *message; struct logfile *next; } logfile; logfile *insertLoglogfile(logfile *info, char *timestamp, char *logLevel, char *message) { logfile *temp = malloc(sizeof(logfile)); // 为每个字符串分配独立内存并复制内容 temp->timestamp = strdup(timestamp); temp->logLevel = strdup(logLevel); temp->message = strdup(message); temp->next = NULL; if (info == NULL) { info = temp; return info; } logfile *current = info; while (current->next != NULL) { current = current->next; } current->next = temp; return info; } void displayLoglogfile(logfile *info) { logfile *current = info; while (current != NULL) { printf("\nTimestamp: %s\nLog level: %s\nMessage: %s\n", current->timestamp, current->logLevel, current->message); current = current->next; } } // 添加内存释放函数,避免泄漏 void freeLoglogfile(logfile *info) { logfile *temp; while (info != NULL) { temp = info; info = info->next; // 先释放字符串内存 free(temp->timestamp); free(temp->logLevel); free(temp->message); // 再释放节点本身 free(temp); } } int main() { logfile *info = NULL; char timestamp[20]; char logLevel[20]; char message[100]; int size; scanf("%d", &size); for (int i = 0; i < size; i++) { scanf("\n"); scanf("[%[^\]] %*c %s %[^\n]", timestamp, logLevel, message); info = insertLoglogfile(info, timestamp, logLevel, message); } displayLoglogfile(info); // 释放内存 freeLoglogfile(info); return 0; }
修改说明
- 字符串内存分配:使用
strdup函数为每个节点的字符串成员分配独立的堆内存,并复制输入的字符串内容,确保每个节点持有独立的字符串副本,不再依赖栈上的固定数组。- 若编译器不支持
strdup(非POSIX环境),可替换为malloc+strcpy的组合:temp->timestamp = malloc(strlen(timestamp) + 1); if (temp->timestamp != NULL) strcpy(temp->timestamp, timestamp);
- 若编译器不支持
- 内存泄漏修复:添加
freeLoglogfile函数,遍历链表时先释放每个节点的字符串内存,再释放节点本身,避免程序退出时的内存泄漏。
内容的提问来源于stack exchange,提问作者Shrinath Korajkar
相关产品推荐
相关产品推荐

