简体   繁体   English

应用在释放内存时出现分段错误

[英]App gives segmentation fault while freeing memory

I have these two files: 我有这两个文件:

test.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

test.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;
}

I am using the gcc -Wall -ggdb test.c -o test command to compile it. 我正在使用gcc -Wall -ggdb test.c -o test命令进行编译。

When I try to run it, it gives me a segmentation fault when freeing memory, what is wrong here? 当我尝试运行它时,释放内存时出现段错误,这是怎么回事?

You need to initialize the node : 您需要初始化node

vertex_node *node = NULL;

If you do not initialize like this, the check: 如果不这样初始化,请检查:

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

will fail for the first call and this part is executed: 第一次调用将失败,并且将执行以下部分:

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

with an arbitrary value in node . node具有任意值。 You can get seg-fault at this time, or when you try to free the node (if you are unlucky). 此时,或者尝试释放节点时(如果不走运),您可能会遇到段错误。

Variables on the stack are not zero-initialized. 堆栈上的变量未初始化为零。 Try the following: 请尝试以下操作:

vertex_node *node = NULL;

Vertex-node should be set to NULL explicitly. 顶点节点应显式设置为NULL。 The error you get is probably due to freeing non malloc-ated memory. 您得到的错误可能是由于释放了未分配的内存。

您必须在dty_vertex检查*node本身是否为NULL

You're freeing non-heap memory. 您正在释放非堆内存。 Stack memory is freed when the function exits. 该函数退出时,将释放堆栈内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM