c语言中的char* 和 malloc 、free的用法

默认分类 · 2013-03-12

今天折腾的时候,发现一个莫名其妙的错误,整了半天解决了,下面是过程。

一、示例程序 test.c

/*test.c*/
int main(int argc, char * argv[])
{
  char * tmd;
  tmd = malloc ( 10 ); 
  tmd = "测试";
  printf ( "%s\n",tmd );
  free ( tmd ); 
}

二、编译:

gcc test.c -o test

三、运行

./test

四、报错

测试
*** glibc detected *** ./1: munmap_chunk(): invalid pointer: 0x00000000004007f4 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x7fb7cdf12b96]
./1[0x400679]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7fb7cdeb576d]
./1[0x400559]
======= Memory map: ========
00400000-00401000 r-xp 00000000 08:09 466018                             /home/iamdsy/jzl_client_git_flow/jzl_client_daemon_make_video/test/1
00600000-00601000 r--p 00000000 08:09 466018                             /home/iamdsy/jzl_client_git_flow/jzl_client_daemon_make_video/test/1
00601000-00602000 rw-p 00001000 08:09 466018                             /home/iamdsy/jzl_client_git_flow/jzl_client_daemon_make_video/test/1
0206e000-0208f000 rw-p 00000000 00:00 0                                  [heap]
7fb7cdc7e000-7fb7cdc93000 r-xp 00000000 08:09 726503                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fb7cdc93000-7fb7cde92000 ---p 00015000 08:09 726503                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fb7cde92000-7fb7cde93000 r--p 00014000 08:09 726503                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fb7cde93000-7fb7cde94000 rw-p 00015000 08:09 726503                     /lib/x86_64-linux-gnu/libgcc_s.so.1
7fb7cde94000-7fb7ce049000 r-xp 00000000 08:09 726483                     /lib/x86_64-linux-gnu/libc-2.15.so
7fb7ce049000-7fb7ce248000 ---p 001b5000 08:09 726483                     /lib/x86_64-linux-gnu/libc-2.15.so
7fb7ce248000-7fb7ce24c000 r--p 001b4000 08:09 726483                     /lib/x86_64-linux-gnu/libc-2.15.so
7fb7ce24c000-7fb7ce24e000 rw-p 001b8000 08:09 726483                     /lib/x86_64-linux-gnu/libc-2.15.so
7fb7ce24e000-7fb7ce253000 rw-p 00000000 00:00 0 
7fb7ce253000-7fb7ce275000 r-xp 00000000 08:09 726465                     /lib/x86_64-linux-gnu/ld-2.15.so
7fb7ce453000-7fb7ce456000 rw-p 00000000 00:00 0 
7fb7ce471000-7fb7ce475000 rw-p 00000000 00:00 0 
7fb7ce475000-7fb7ce476000 r--p 00022000 08:09 726465                     /lib/x86_64-linux-gnu/ld-2.15.so
7fb7ce476000-7fb7ce478000 rw-p 00023000 08:09 726465                     /lib/x86_64-linux-gnu/ld-2.15.so
7fffe4f37000-7fffe4f58000 rw-p 00000000 00:00 0                          [stack]
7fffe4fff000-7fffe5000000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted

五、解决办法

示例程序修改如下,似乎就没问题了

/*test.c*/
int main(int argc, char * argv[])
{
  char * tmd;
  tmd = "测试";
  printf ( "%s\n",tmd );
}
编程 c语言
Theme Jasmine by Kent Liao