【发布时间】:2012-08-20 22:24:52
【问题描述】:
我尝试创建一个函数,用str2 替换文本t 中所有出现的str1,但我不断收到“缓冲区溢出” 错误消息。你能告诉我我的功能有什么问题吗?
#include <stdio.h>
#include <string.h>
#include <assert.h>
//replace all *str1 in *t with *str2, put the result in *x, return *x
char * result(char *str1,char *str2,char *t)
{
char *x=NULL,*p=t,*r=t;
x=malloc(400*sizeof(char));
assert(x!=NULL);
x[0]='\0';
r=strstr(t,str1); //r is at the first occurrence of str1 in t, p is at the beginning of t
while(r!=NULL)
{
strncat(x,p,r-p); //copy r-p chars from p to x
strcat(x,str2); //copy str2 to x
p=r+strlen(str1); //p will be at the first char after the last occurrence of str1 in t
r=strstr(r+strlen(str1),str1); //r goes to the next occurrence of str1 in t
}
strcat(x,p);
return x;
}
我没有使用gets() 函数读取任何char 数组。
我的编译器是 gcc 版本 4.6.3
我更新了代码,它可以工作,但结果不是预期的。
main()函数:
int main(void)
{
char *sir="ab",*sir2="xyz",*text="cabwnab4jkab",*final;
final=result(sir,sir2,text);
puts(final);
free(final);
return 0;
}
打印字符串:
b
我期待cxyzwnxyz4jkxyz
【问题讨论】:
-
你不能返回
x,它是函数本地的。 -
查看编辑:你的结果和
strcatvs.strcpy -
在调试器中单步执行此代码或每次通过循环打印出变量的值应该可以相当清楚问题出在哪里。
-
sizeof(char)是 C 中的定义 1。虽然它是一种次要的风格,但它表明你对语言的理解存在更深层次的问题。
标签: c string char buffer-overflow