C缓冲区溢出

标签 c string char buffer-overflow

我试图制作一个函数,将文本 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/

相关文章:

c - 叉(); C 中的方法 : determine order

eclipse - 停止 Eclipse 重命名字符串内部

android - 对于区域设置 "ar"(阿拉伯语),还应定义以下数量 : few, 多个、两个、零

c - char数组的问题= char数组

c - C 中 "big"字符十六进制常量的值是多少?

c - 在头部被删除并重新创建后创建列表的第二个元素时出错

C 2D Arrays 通过移动其下方的行来删除某些预定行

c - 尝试终止一个字符数组并在之后打印

c - 为什么FIQ需要用汇编语言而不是C语言编写?

sql - 如何在 Postgresql 中创建一个巨大的字符串