我试图制作一个函数,将文本 t
中所有出现的 str1
替换为 str2
但我一直得到 “缓冲区溢出” 错误消息。你能告诉我我的功能有什么问题吗?
#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
最佳答案
看起来你已经得到了你的 strncpy
参数混淆:第二个参数是 source 字符串,不是要复制的字符数限制,它应该是第三个参数:
strncpy(x, p, r - p); // copy r - p chars from p to x
此外,您想使用 strcat
而不是 strcpy
。使用 strcpy
,您每次都将用替换字符串覆盖结果的内容。使用strcat
,一定要在开始前用\0
初始化结果。
最后,您要从函数返回对局部变量 x
的引用:您不能这样做,因为函数返回后内存不可用。
关于C缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12046068/