Thread: Segfault when trying to free a double linked list

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    13

    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
    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)
          exit_rep_error();
        if(first_lista_cont->next != NULL) {
          first_lista_cont = first_lista_cont->next;
          free(first_lista_cont->prev);
        }
        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
    Location
    Oregon, USA
    Posts
    3,218
    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:
    Code:
    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);
    
      free(ptr);
      printf("ptr points to %p\n", ptr);
    
      return 0;
    }
    Code:
    itsme@itsme:~/C$ ./free
    ptr points to 0xb8000900
    ptr points to 0x804a050
    ptr points to 0x804a050
    itsme@itsme:~/C$
    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