Valgrind在使用realloc函数时抱怨?

Valgrind在使用realloc函数时抱怨?,c,string,valgrind,C,String,Valgrind,我已经实现了自己版本的strcat函数。 它工作得很好,但valgrind抱怨道 main() { char *src=NULL; src=(char *) malloc(sizeof(char)*8); strcpy(src,"sandeep"); xstrcat(src,"pathak"); printf("******FINAL STR IS : %s ********",src); free(src); src=NULL; }

我已经实现了自己版本的strcat函数。
它工作得很好,但valgrind抱怨道

main()
{
    char *src=NULL;
    src=(char *) malloc(sizeof(char)*8);
    strcpy(src,"sandeep");
    xstrcat(src,"pathak");
    printf("******FINAL STR IS : %s ********",src);
    free(src);
    src=NULL; 
}

void  xstrcat(char *src,const char *dest)
{
        int dlen=strlen(dest);
        int slen=strlen(src);
        int j=0;
        int i=0;
        char *temp=(char *) realloc(src,(slen+dlen+1)*sizeof(char));
        for(j=slen;i<dlen;i++,j++)
        {
                temp[j]=dest[i];
        }
        temp[j]='\0';
        printf("%s",temp);
}
我已经释放了src,但是使用realloc会导致这个问题

任何帮助都将不胜感激

void xstrcat(char *src,const char *dest) {
您正在按值传递src,xstrcat正在处理并修改其本地副本。对
src
所做的任何更改都不会反映在调用函数中

void xstrcat(char **src,const char *dest) {
  // Work with *src
}

...
xstrcat(&src, ...)
这种方法允许xstrcat修改main的
src
变量

引用一个经常提到的示例:

void foo (int x) {
  x = 2;
}
void bar (int * x) {
  *x = 2;
}
int main() {
  foo(9); // foo cannot modify the literal 9
  int i = 1;
  foo(i); // foo cannot modify the variable i
  bar(&9); // This isn't legal - it can't be
  bar(&i); // bar modifies i
}

我正在更改str指向的块(内容),而不是引用,因此没有必要出现上述问题……上述代码工作正常,请帮助我解决Valgrind问题。。。。thanks@Sandeep当前位置埃里克是对的。当您realloc
src
时,很幸运,包含您已经拥有的分配的底层块恰好足够大,可以容纳新的大小,因此新地址
temp
src
相同,
src
仍然指向您想要的数据。这不是
realloc
的正常行为。尝试重新分配到更大的大小,那么您的代码将失败。
newvar=realloc(oldvar,…)
相当于
char*newvar=malloc(…);memcpy(newvar、oldvar);免费(oldvar)-您正在释放原始的
src
,main永远不会知道这一点,不要
src
是来源:事物从何而来<代码>目的地
是目的地:事物的去向to@pmg:但它会产生如此有趣的bug…请不要使用malloc()的返回值;sizeof(char)始终为1。
void foo (int x) {
  x = 2;
}
void bar (int * x) {
  *x = 2;
}
int main() {
  foo(9); // foo cannot modify the literal 9
  int i = 1;
  foo(i); // foo cannot modify the variable i
  bar(&9); // This isn't legal - it can't be
  bar(&i); // bar modifies i
}