strcat对字符串的处理问题!
#include <time.h>
#include <stdio.h>
void getCurrentTime(char *str);
int main(){
char myTime[30];
char *tmpStr=NULL;
getCurrentTime(myTime);
printf( "Current time: %s\n ",myTime);
tmpStr=malloc(strlen(fileName)+1);
strcat(tmpStr,fileName);
printf( "Second point: %s\n ",tmpStr);
free(tmpStr);
return 0;
}
void getCurrentTime(char *str){
time_t now;
struct tm *timenow;
time(&now);
timenow=localtime(&now);
strftime(str,30, "%Y%m%d%H%M%S ",timenow);
}
在主函数中用strcat对myTime进行处理,编译能通过,但是时总会出现如下结果:
Current time:20070717131311
Second point: PcBPcB????20070717131311
*** glibc detected *** /home/netlink/test2/subtime: free(): invalid next size (fast): 0x08f1b050 ***
======= Backtrace: =========
/lib/libc.so.6[0x4255befd]
/lib/libc.so.6(cfree+0x90)[0x4255f550]
/home/netlink/test2/subtime[0x804859e]
/lib/libc.so.6(__libc_start_main+0xdc)[0x4250bf2c]
/home/netlink/test2/subtime[0x80483f1]
======= Memory map: ========
00fdd000-00fde000 r-xp 00fdd000 00:00 0 [vdso]
08048000-08049000 r-xp 00000000 fd:00 979310 /home/netlink/test2/subtime
08049000-0804a000 rwxp 00000000 fd:00 979310 /home/netlink/test2/subtime
08f1b000-08f3c000 rwxp 08f1b000 00:00 0
41b27000-41b40000 r-xp 00000000 fd:00 558656 /lib/ld-2.5.so
41b40000-41b41000 r-xp 00018000 fd:00 558656 /lib/ld-2.5.so
41b41000-41b42000 rwxp 00019000 fd:00 558656 /lib/ld-2.5.so
424f6000-4262d000 r-xp 00000000 fd:00 558657 /lib/libc-2.5.so
4262d000-4262f000 r-xp 00137000 fd:00 558657 /lib/libc-2.5.so
4262f000-42630000 rwxp 00139000 fd:00 558657 /lib/libc-2.5.so
42630000-42633000 rwxp 42630000 00:00 0
430a3000-430ae000 r-xp 00000000 fd:00 558679 /lib/libgcc_s-4.1.1-20061011.so.1
430ae000-430af000 rwxp 0000a000 fd:00 558679 /lib/libgcc_s-4.1.1-20061011.so.1
b7e00000-b7e21000 rw-p b7e00000 00:00 0
b7e21000-b7f00000 ---p b7e21000 00:00 0
b7f21000-b7f22000 rw-p b7f21000 00:00 0
b7f2e000-b7f30000 rw-p b7f2e000 00:00 0
bfd16000-bfd2b000 rw-p bfd16000 00:00 0 [stack]
在打印tmpStr时,出现额外乱码-> PcBPcB????,还有就是后面的free()的错
直接定义的字符串例如
char *s1= "this is first! ";
char *s2= "this is last! ";
用strcat对上面两个字符串处理是,不会出现异常输出,但只要对从getCurrentTime()函数中获得的字符串进行操作,就会出现上述错误.
------解决方案--------------------
你的fileName在哪里定义的啊
[解决办法]
tmpStr分配是不成功,是否有足够的空间存储
[解决办法]
1.main函数里的fileName未定义,可以通过编译吗?
2.输出时有乱码是因为tmpStr分配内存成功后并未初始化.
3.strcat(tmpStr,fileName); 这句执行后,tmpStr指向的地址长度发生了变化,执行free(tmpStr时);释放内存时就会释放过多的内存.
4.动态分配内存时最好是进行强制类型转换后再赋值,分配后要判断是否成功.这是一个好习惯.
[解决办法]
你的tmpStr里边什么都没有啊
当然是乱码啦
[解决办法]
造成 乱码和free 出错的原因,
可能是因为 malloc 申请的空间不足。