在对struct 类型的使用时,要注意对其进行初始化,特别是其中的指针类型。
因为在对已定义的struct的函数调用当中,会出现对它的进行非空判断后释放内存的危险行为。
如下例:
gcc编译后的执行结果为:
sea@sea-server:~/testcode$ ./a.out
Try free!!!
*** glibc detected *** ./a.out: free(): invalid pointer: 0xb7f63ff4 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6[0xb7e84a85]
/lib/tls/i686/cmov/libc.so.6(cfree+0x90)[0xb7e884f0]
./a.out[0x8048443]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe0)[0xb7e2f450]
./a.out[0x80483b1]
======= Memory map: ========
08048000-08049000 r-xp 00000000 08:01 2105525 /home/sea/testcode/a.out
08049000-0804a000 rw-p 00000000 08:01 2105525 /home/sea/testcode/a.out
0804a000-0806b000 rw-p 0804a000 00:00 0 [heap]
b7e18000-b7e19000 rw-p b7e18000 00:00 0
b7e19000-b7f62000 r-xp 00000000 08:01 4383783 /lib/tls/i686/cmov/libc-2.7.so
b7f62000-b7f63000 r--p 00149000 08:01 4383783 /lib/tls/i686/cmov/libc-2.7.so
b7f63000-b7f65000 rw-p 0014a000 08:01 4383783 /lib/tls/i686/cmov/libc-2.7.so
b7f65000-b7f68000 rw-p b7f65000 00:00 0
b7f69000-b7f73000 r-xp 00000000 08:01 4366357 /lib/libgcc_s.so.1
b7f73000-b7f74000 rw-p 0000a000 08:01 4366357 /lib/libgcc_s.so.1
b7f74000-b7f77000 rw-p b7f74000 00:00 0
b7f77000-b7f78000 r-xp b7f77000 00:00 0 [vdso]
b7f78000-b7f92000 r-xp 00000000 08:01 4366348 /lib/ld-2.7.so
b7f92000-b7f94000 rw-p 00019000 08:01 4366348 /lib/ld-2.7.so
bfdb2000-bfdc7000 rw-p bffeb000 00:00 0 [stack]
Aborted
对这种错误,唯有在定义struct的时候,进行细致的初始化:
sConfig.category = sConfig.name = sConfig.element = sConfig.type = sConfig.value = NULL;