c - 列表列表(内部列表被删除或内存释放)

标签 c list memory

我使用基于 C 的网络模拟器 OPNET。在我的一个 C 文件(称为进程模型)中,我有一个全局可访问的链接列表(称为障碍列表)。在下面的代码中,我用包含字符串的较小列表填充它。这似乎工作正常,我可以在最后读回整个列表。

但是,稍后我需要从另一个 C 文件(进程模型)访问这个全局列表列表。

当我尝试访问这个全局链表时,我可以看到它包含 380 个项目(正确),但当我尝试访问内部链表时,它们是空的。

当我第一天填充列表时,这一定是内存分配的疏忽。当我使用“input = op_prg_list_create()”行创建内部列表并使用 strdup 为列表内容分配内存时,我不明白为什么会发生这种情况。

我对此非常困惑,因此任何有关可能发生的情况的帮助或指示将不胜感激。

非常感谢。

fgets(line, sizeof(line), obstaclePositions_traj_file);

obstacle_list = op_prg_list_create();

while (line != OPC_NIL) 
{
token = strtok(line, "\t\n"); //Pull the string apart into tokens using the \t
input = op_prg_list_create();

while (token != NULL)
       {
          test_token = strdup(token);

          if (op_prg_list_size(input) == 0)
           op_prg_list_insert(input,test_token,OPC_LISTPOS_HEAD);
          else
           op_prg_list_insert(input,test_token,OPC_LISTPOS_TAIL);
      token = strtok (NULL, "\t\n");
      }     

       if (op_prg_list_size(obstacle_list) == 0)
    op_prg_list_insert(obstacle_list,input,OPC_LISTPOS_HEAD);
   else
    op_prg_list_insert(obstacle_list,input,OPC_LISTPOS_TAIL);

}


//check the list has been populated correctly below (it has)

/*size_ob_list = op_prg_list_size (obstacle_list);
for (k = 0; k <size_ob_list; k++)
{
line_coord_list = (List*)op_prg_list_access (obstacle_list, k);     
count_inner_list = op_prg_list_size (line_coord_list);
for (j=0; j< count_inner_list; j++)
{
    coords = (char*)op_prg_list_access (line_coord_list, j);
    printf("%c", coords);       
}
}*/

最佳答案

while (line != OPC_NIL) {} 可疑。

在 EOF 上,fgets() 返回 null,但不改变缓冲区(最后一次成功调用的内容仍将在那里)

obstacle_list = op_prg_list_create();

while (fgets(line, sizeof(line), obstaclePositions_traj_file) )
{
    input = op_prg_list_create();

    for( token = strtok(line, "\t\n"); token ; token = strtok (NULL, "\t\n") )
       {
          test_token = strdup(token);

          op_prg_list_insert(input,test_token
            , (op_prg_list_size(input)==0) ? OPC_LISTPOS_HEAD : OPC_LISTPOS_TAIL
            );
    }     

    op_prg_list_insert(obstacle_list,input
     , (op_prg_list_size(obstacle_list) == 0) ? OPC_LISTPOS_HEAD : OPC_LISTPOS_TAIL
     );

}

关于c - 列表列表(内部列表被删除或内存释放),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14910537/

相关文章:

python - 减少专用于 pandas dtype=object 的内存

c++ - 如何避免编写同一个循环的多个版本

c++ - 如何使用 CTypes 将 wchar_t**(UNICODE 字符串的 null 终止数组)返回到 Python 脚本

list - Scala模式匹配: How to match on an element inside a list?

go - golang程序内存不断增长,但只有一点inuse_space

android - 使用已完成的 Activity 和低 kb 图像获取 OutofMemoryError/InvocationTargetException?

java - 在 Java 中使用 FUSE 库;尝试复制 hello.c 示例

c - 将时间信息从 NTP 服务器传递到 strftime 函数

java - 更改 Java 列表中的引用

python - 如何反转子列表中的元素?