Wanderson Silva
Wanderson Silva

Reputation: 1199

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.

When I try to run it, it gives me a segmentation fault when freeing memory, what is wrong here?

Upvotes: 0

Views: 132

Answers (5)

perreal
perreal

Reputation: 98048

You need to initialize the 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. You can get seg-fault at this time, or when you try to free the node (if you are unlucky).

Upvotes: 3

Claudiu
Claudiu

Reputation: 229461

You have to check for *node itself being NULL in dty_vertex.

Upvotes: 0

LSerni
LSerni

Reputation: 57418

Vertex-node should be set to NULL explicitly. The error you get is probably due to freeing non malloc-ated memory.

Upvotes: 1

Razvan
Razvan

Reputation: 10093

You're freeing non-heap memory. Stack memory is freed when the function exits.

Upvotes: 0

user1202136
user1202136

Reputation: 11567

Variables on the stack are not zero-initialized. Try the following:

vertex_node *node = NULL;

Upvotes: 3

Related Questions