delete dynamically allocated memory in a list?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • akywy
    New Member
    • Aug 2006
    • 1

    #1

    delete dynamically allocated memory in a list?

    Two questions about the following code sample:

    --- code begins ---
    //class IPv4 is defined elsewhere

    list<IPv4> ip_list;

    for (int i=1; i<=9; i++) {
    char addr[128];
    sprintf(addr, "%d.%d.%d.% d", i,i,i,i);

    //IPv4 new_ip(addr);
    //ip_list.push_ba ck(new_ip);
    ptr = new IPv4(addr);
    ip_list.push_ba ck(*ptr);
    }

    ...

    list<IPv4>::ite rator k;
    k = ip_list.begin() ;
    while (k!=pp_list.end ()) {
    delete &pp_list.front( );
    pp_list.pop_fro nt();
    k = pp_list.begin() ;
    }

    --- code ends ---
    When I try to free the memory using delete, the program run into error saying "double free or corruption". I don't know why. How am I supposed to delete the dynamically allocated memory in a list?

    By the way, if I use the two statement that are currently commented in the first for loop instead of the two statements below them, I don't need to worry about freeing the memory, right?

    Thanks!
  • D_C
    Contributor
    • Jun 2006
    • 293

    #2
    Why do you have two lists, ip_list and pp_list? Also, you delete the pointer to the first list element, then instruct the program to remove the first list element whose pointer you just deleted? Why?

    Comment

    Working...