c - 应用程序在释放内存时出现段错误

标签 c malloc free

我有这两个文件:

测试.h

#ifndef TEST_H
#define TEST_H

typedef struct _vertex_node
{
  double x;
  double y;
  struct _vertex_node *next;
} vertex_node;

static void add_vertex(vertex_node **node, const double x, const double y);
static void dty_vertex(vertex_node **node);

#endif // TEST_H

测试.c

#include <stdio.h>
#include <stdlib.h>

#include "test.h"


static void add_vertex(vertex_node **node, const double x, const double y)
{
  if(NULL == (*node))
  {
    (*node) = malloc(sizeof(vertex_node));
    (*node)->x = x;
    (*node)->y = y;
    (*node)->next = NULL;
  }
  else
    add_vertex(&((*node)->next), x, y);
}

static void dty_vertex(vertex_node **node)
{
  if(NULL != (*node)->next)
    dty_vertex(&((*node)->next));

  free(*node);
}

int main(int argc, char **argv)
{
  vertex_node *node;
  vertex_node *iterator;

  add_vertex(&node, 0, 0);
  add_vertex(&node, 1, 0);
  add_vertex(&node, 1, 1);
  add_vertex(&node, 0, 1);

  iterator = node;

  while(NULL != iterator)
  {
    printf("x: %f, y: %f\n", iterator->x, iterator->y);

    iterator = iterator->next;
  }

  dty_vertex(&node);

  return 0;
}

我正在使用 gcc -Wall -ggdb test.c -o test 命令来编译它。

当我尝试运行它时,它在释放内存时给我一个段错误,这里出了什么问题?

最佳答案

您需要初始化节点:

vertex_node *node = NULL;

如果你没有像这样初始化,检查:

if(NULL == (*node))
  { /* */ }

第一次调用会失败,这部分会被执行:

add_vertex(&((*node)->next), x, y);

node 中具有任意值。您可能会在此时遇到段错误,或者当您尝试释放节点时(如果您不走运的话)。

关于c - 应用程序在释放内存时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11955647/

相关文章:

c - 放宽 visual-studio C 编译器语法

c - realloc() 结构数组的旧大小无效

c - C 中的自由链表

c - C, "void main (int argc, char *argv[0])"是什么,注意 argv 中的零

c - 反向 C 字符串 - 简单的错误

c - 将 GTK 窗口放在屏幕的一角

转换数组以使用 malloc

c - 如何释放前缀树中的内存? (美国标准 C)

c - 内存分配C

c - 已经释放内存