- 论坛徽章:
- 0
|
我写了个函数,目的是删除字符串里的空格符。遇到了很奇怪的问题。如下
失败的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void strip(char *);
void strip (char *str)
{
int num=0;
char *head =str;
char *temp = str;
while (*temp++) num++;
char *a = (char *)malloc(num*sizeof(char));
if (a != NULL)
{
while (*str)
{
if (*str == ' ')
{
str++;
continue;
}
*a++ = *str++;
}
*a = '\0';
strcpy(head,a);
free(a);
}
else
puts("NULL pointer");
}
main()
{
char name[]="ldkfkdfkdf fdf 1";
strip(name);
puts(name);
}
执行后报告错误
*** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0x000000000b57901e ***
======= Backtrace: =========
/lib64/libc.so.6(cfree+0x166)[0x3848272856]
./a.out[0x40060f]
./a.out[0x40064f]
/lib64/libc.so.6(__libc_start_main+0xf4)[0x384821d994]
./a.out[0x4004b9]
======= Memory map: ========
00400000-00401000 r-xp 00000000 03:01 6828567 /tmp/a.out
00600000-00601000 rw-p 00000000 03:01 6828567 /tmp/a.out
0b579000-0b59a000 rw-p 0b579000 00:00 0 [heap]
3847e00000-3847e1c000 r-xp 00000000 03:01 4737748 /lib64/ld-2.5.so
384801b000-384801c000 r--p 0001b000 03:01 4737748 /lib64/ld-2.5.so
384801c000-384801d000 rw-p 0001c000 03:01 4737748 /lib64/ld-2.5.so
3848200000-384834d000 r-xp 00000000 03:01 4737749 /lib64/libc-2.5.so
384834d000-384854d000 ---p 0014d000 03:01 4737749 /lib64/libc-2.5.so
384854d000-3848551000 r--p 0014d000 03:01 4737749 /lib64/libc-2.5.so
3848551000-3848552000 rw-p 00151000 03:01 4737749 /lib64/libc-2.5.so
3848552000-3848557000 rw-p 3848552000 00:00 0
384a600000-384a60d000 r-xp 00000000 03:01 4737758 /lib64/libgcc_s-4.1.2-20080825.so.1
384a60d000-384a80d000 ---p 0000d000 03:01 4737758 /lib64/libgcc_s-4.1.2-20080825.so.1
384a80d000-384a80e000 rw-p 0000d000 03:01 4737758 /lib64/libgcc_s-4.1.2-20080825.so.1
2ab4b52c7000-2ab4b52c8000 rw-p 2ab4b52c7000 00:00 0
2ab4b52da000-2ab4b52dc000 rw-p 2ab4b52da000 00:00 0
7fff38173000-7fff38188000 rw-p 7ffffffea000 00:00 0 [stack]
ffffffffff600000-ffffffffffe00000 ---p 00000000 00:00 0 [vdso]
Aborted
################
以下是我换了数组的方式写了个
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void strip(char *);
void strip (char *str)
{
int i=0;
char *head =str;
char temp[40];
while (*str)
{
if (*str == ' ')
{
str++;
continue;
}
temp[i] = *str++;
i++;
}
temp[i] = '\0';
strcpy(head,temp);
}
main()
{
char name[]="ldkfkdfkdf fdf 1";
strip(name);
puts(name);
}
执行后是好的。结果是:ldkfkdfkdffdf1 ,空格没了。
我查了下,非常奇怪,第一个失败是往malloc分配内存的空间里写数据出的问题。
我是刚开始写C,求高手赐教,为啥第一是失败的?不胜感激 |
|