views:

63

answers:

1

I am learning socket programming under Linux,so I make a sample program to list all the network interface,here is the code

/* print the name of interface */
#include <sys/socket.h>
#include <net/if.h>
#include <stdio.h>

int
main(void)
{
 struct if_nameindex *pif;

 pif = if_nameindex();
 while (pif->if_index) {
  printf("name: %s \t index: %d\n", pif->if_name, pif->if_index);
  pif++;
 }

 if_freenameindex(pif);

 printf("after the first if_freenameindex call\n");

 return 0;
}

run it and it returns

name: lo   index: 1
name: eth0   index: 2
name: eth1   index: 3
name: eth2   index: 4
*** glibc detected *** ./if: double free or corruption (out): 0x0983b420 ***
======= Backtrace: =========
/lib/i686/cmov/libc.so.6[0xb7edb624]
/lib/i686/cmov/libc.so.6(cfree+0x96)[0xb7edd826]
/lib/i686/cmov/libc.so.6(if_freenameindex+0x40)[0xb7f6f9e0]
./if[0x80484b6]
/lib/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb7e83455]
./if[0x80483d1]
======= Memory map: ========
08048000-08049000 r-xp 00000000 03:01 51169      /home/jcyang/src/net/gnu/if
08049000-0804a000 rw-p 00000000 03:01 51169      /home/jcyang/src/net/gnu/if
0983b000-0985c000 rw-p 0983b000 00:00 0          [heap]
b7d00000-b7d21000 rw-p b7d00000 00:00 0 
b7d21000-b7e00000 ---p b7d21000 00:00 0 
b7e54000-b7e60000 r-xp 00000000 03:01 73587      /lib/libgcc_s.so.1
b7e60000-b7e61000 rw-p 0000b000 03:01 73587      /lib/libgcc_s.so.1
b7e6c000-b7e6d000 rw-p b7e6c000 00:00 0 
b7e6d000-b7fc2000 r-xp 00000000 03:01 82774      /lib/i686/cmov/libc-2.7.so
b7fc2000-b7fc3000 r--p 00155000 03:01 82774      /lib/i686/cmov/libc-2.7.so
b7fc3000-b7fc5000 rw-p 00156000 03:01 82774      /lib/i686/cmov/libc-2.7.so
b7fc5000-b7fc9000 rw-p b7fc5000 00:00 0 
b7fd3000-b7fd5000 rw-p b7fd3000 00:00 0 
b7fd5000-b7fd6000 r-xp b7fd5000 00:00 0          [vdso]
b7fd6000-b7ff0000 r-xp 00000000 03:01 73586      /lib/ld-2.7.so
b7ff0000-b7ff2000 rw-p 0001a000 03:01 73586      /lib/ld-2.7.so
bffdc000-bfff1000 rw-p bffeb000 00:00 0          [stack]
Aborted

Acoording to the GNU C Library Reference Manaul,we should use if_freenameindex to free the earily returned if_nameindex.So whats wrong?

thanks.

+2  A: 

You should call if_freenameindex() on first pif, not the final one. for example:

struct if_nameindex *pif;
struct if_nameindex *head;
head = pif = if_nameindex(); 
while (pif->if_index) { 
   printf("name: %s \t index: %d\n", pif->if_name, pif->if_index); 
   pif++; 
} 

if_freenameindex(head); 
....
EffoStaff Effo