You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

复制字符指针时出现内存泄漏问题求助

问题分析与修复

内存泄漏的核心原因

  1. 丢失strdup分配的内存首地址:strsep会修改传入的指针(也就是你的newline变量),每次分割后newline会指向剩余字符串的起始位置,循环结束时newline会被置为NULL。此时调用free(newline)相当于释放空指针,完全没触碰到strdup分配的那块原始内存,这就是泄漏的根源。
  2. 非法释放found指针:strsep返回的found是指向newline内存块内部的指针,并非通过malloc/strdup单独分配的,调用free(found)属于非法内存操作,会导致未定义行为。

修复后的代码

struct Item {
    char* line;
    struct Item *next;
};

struct Item* getArguments(char *line) {
  struct Item *current = NULL;
  struct Item *next = NULL;
  struct Item *first = NULL;
  char *found = NULL;
  char *newline = strdup(line);
  // 保存strdup返回的原始内存地址,避免被strsep修改后丢失
  char *orig_newline = newline;
  
  while ((found = strsep(&newline," \n")) != NULL) {
      // 直接判断空字符串,无需额外定义blank数组
      if (*found != '\0') {
        next = malloc(sizeof(struct Item));
        next->next = NULL;
        // 用strdup简化内存分配与复制
        next->line = strdup(found);
        
        if (current) {
          current->next = next;
        }
        current = next;
        if (first == NULL) {
          first = current;
        }
      }
  }
  
  free(orig_newline); // 释放strdup分配的原始内存
  return first;
}

额外说明

  • 修复代码里用*found != '\0'代替strcmp判断空字符串,效率更高;用strdup替代malloc+strcpy,简化代码逻辑。
  • 注意:调用getArguments后,需要遍历返回的链表,逐个释放每个Item的line指针和Item结构体本身,避免新的内存泄漏。

内容的提问来源于stack exchange,提问作者Gengar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:41:33