C缓冲区溢出

Cri*_*sti 4 c string char buffer-overflow

我试图让替换所有出现的功能str1在文本tstr2,但我不断收到一个"缓冲区溢出"错误消息.你能告诉我我的功能有什么问题吗?

#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;
}
Run Code Online (Sandbox Code Playgroud)

我没有使用该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;
}
Run Code Online (Sandbox Code Playgroud)

打印字符串:

b
Run Code Online (Sandbox Code Playgroud)

我期望 cxyzwnxyz4jkxyz

pb2*_*b2q 7

看起来你的strncpy论点已经混淆了:第二个参数是字符串,而不是要复制的字符数限制,这应该是第三个参数:

 strncpy(x, p, r - p); // copy r - p chars from p to x
Run Code Online (Sandbox Code Playgroud)

此外,您想要使用strcat而不是strcpy.使用时strcpy,每次都只用替换字符串覆盖结果的内容.使用时strcat,请务必\0在开始之前初始化结果.

最后,您x将从函数返回对局部变量的引用:您无法执行此操作,因为函数返回后内存不可用.