Thread: Segfault when trying to free a double linked list

  1. #1
    Registered User
    Join Date
    Apr 2004

    Segfault when trying to free a double linked list

    hi there!
    i'm working on a project where i want to insert the elements of a double linked list in a database to which i have the interaction commands...
    in the execution of this code
    void actualizar_db() {
      while(first_lista_cont != NULL) {
        if(append_record(first_lista_cont->nome, first_lista_cont->morada, first_lista_cont->cod_postal,
    		     first_lista_cont->telefone, first_lista_cont->idade) == RLERR)
        if(first_lista_cont->next != NULL) {
          first_lista_cont = first_lista_cont->next;
        else {
          free(first_lista_cont); /*this is where i get the segfault*/
    append_record is one of the commands which interacts with the database

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Oregon, USA
    free() does not set the pointer to NULL, so after you call free(first_lista_cont), first_lista_cont still points to the same memory address, but it's invalid. You'll have to set it to NULL yourself after calling free() on it for your while() condition to make sense.

    EDIT: Here's a little program that illustrates what I'm saying:
    itsme@itsme:~/C$ cat free.c
    #include <stdio.h>
    #include <stdlib.h>
    int main(void)
      void *ptr;
      printf("ptr points to %p\n", ptr);
      ptr = malloc(1);
      printf("ptr points to %p\n", ptr);
      printf("ptr points to %p\n", ptr);
      return 0;
    itsme@itsme:~/C$ ./free
    ptr points to 0xb8000900
    ptr points to 0x804a050
    ptr points to 0x804a050
    Last edited by itsme86; 04-19-2005 at 07:42 AM.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Testing some code, lots of errors...
    By Sparrowhawk in forum C Programming
    Replies: 48
    Last Post: 12-15-2008, 04:09 AM
  2. Need some help...
    By darkconvoy in forum C Programming
    Replies: 32
    Last Post: 04-29-2008, 03:33 PM
  3. need some help with last part of arrays
    By Lince in forum C Programming
    Replies: 3
    Last Post: 11-18-2006, 09:13 AM
  4. Replies: 5
    Last Post: 11-04-2006, 06:39 PM
  5. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 06:13 AM