本文共 3310 字,大约阅读时间需要 11 分钟。
1.源码
#includegcc -o test test.c#include #include int main(){ char *test1; test1 = (char *)malloc(8); printf("test1 addr is 0x%lx\n",test1); strncpy(test1,"adbdefg",7); //test1 = "adbdefg"; printf("test1 addr is 0x%lx\n",test1); printf("test1 addr is 0x%lx\n",test1); printf("test1 is %s\n",test1); printf("test1 size is %d\n",sizeof(*test1)); printf("test1 addr size is %d\n",sizeof(test1)); free(test1); test1 = NULL; return 0;}
结果:
test1 addr is 0x255b010test1 addr is 0x255b010test1 addr is 0x255b010test1 is adbdefgtest1 size is 1test1 addr size is 8如果//test1 = "adbdegf"放通,strncpy那句屏蔽;结果如下:
test1 addr is 0x11cd010test1 addr is 0x400751test1 addr is 0x400751test1 is adbdefgtest1 size is 1test1 addr size is 8*** glibc detected *** ./testt: free(): invalid pointer: 0x0000000000400751 ***======= Backtrace: =========/lib/x86_64-linux-gnu/libc.so.6(+0x7ae16)[0x7fc54434ee16]/lib/x86_64-linux-gnu/libc.so.6(cfree+0x6c)[0x7fc5443530fc]./testt[0x400640]/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7fc5442f530d]./testt[0x4004c9]======= Memory map: ========00400000-00401000 r-xp 00000000 08:07 21086431 /home/lianxi/c++/testt00600000-00601000 r--p 00000000 08:07 21086431 /home/lianxi/c++/testt00601000-00602000 rw-p 00001000 08:07 21086431 /home/lianxi/c++/testt011cd000-011ee000 rw-p 00000000 00:00 0 [heap]7fc540000000-7fc540021000 rw-p 00000000 00:00 0 7fc540021000-7fc544000000 ---p 00000000 00:00 0 7fc5440be000-7fc5440d3000 r-xp 00000000 08:05 2050760 /lib/x86_64-linux-gnu/libgcc_s.so.17fc5440d3000-7fc5442d2000 ---p 00015000 08:05 2050760 /lib/x86_64-linux-gnu/libgcc_s.so.17fc5442d2000-7fc5442d3000 r--p 00014000 08:05 2050760 /lib/x86_64-linux-gnu/libgcc_s.so.17fc5442d3000-7fc5442d4000 rw-p 00015000 08:05 2050760 /lib/x86_64-linux-gnu/libgcc_s.so.17fc5442d4000-7fc54446d000 r-xp 00000000 08:05 2048322 /lib/x86_64-linux-gnu/libc-2.13.so7fc54446d000-7fc54466c000 ---p 00199000 08:05 2048322 /lib/x86_64-linux-gnu/libc-2.13.so7fc54466c000-7fc544670000 r--p 00198000 08:05 2048322 /lib/x86_64-linux-gnu/libc-2.13.so7fc544670000-7fc544671000 rw-p 0019c000 08:05 2048322 /lib/x86_64-linux-gnu/libc-2.13.so7fc544671000-7fc544677000 rw-p 00000000 00:00 0 7fc544677000-7fc544698000 r-xp 00000000 08:05 2048320 /lib/x86_64-linux-gnu/ld-2.13.so7fc54486f000-7fc544872000 rw-p 00000000 00:00 0 7fc544894000-7fc544897000 rw-p 00000000 00:00 0 7fc544897000-7fc544898000 r--p 00020000 08:05 2048320 /lib/x86_64-linux-gnu/ld-2.13.so7fc544898000-7fc54489a000 rw-p 00021000 08:05 2048320 /lib/x86_64-linux-gnu/ld-2.13.so7fffd2e0f000-7fffd2e30000 rw-p 00000000 00:00 0 [stack]7fffd2f54000-7fffd2f55000 r-xp 00000000 00:00 0 [vdso]ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]已放弃
2.分析原因
char *test1;
test1 = (char *)malloc(8);//在堆中分配动态内存
test1 = "adbdefg";//"adbdefg"为常量,存储在TEXT存储区域;试图释放该内存会导致异常
free(test1);//使用free函数去释放一个TEXT只读区域内存,程序肯定异常
转载地址:http://aegai.baihongyu.com/