我有这两个文件:
测试.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/