Valgrind在使用realloc函数时抱怨?

时间:2011-03-13 14:08:36

标签: 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; 
}

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);
}

VALGRIND错误:

==31775== Invalid read of size 4
==31775== Invalid read of size 4
==31775== Invalid read of size 1
==31775== Invalid read of size 1
==31775== 14 bytes in 1 blocks are definitely lost in loss record 1 of 1
==31775==    at 0x1B9053EE: realloc (vg_replace_malloc.c:197)
==31775==    by 0x8048606: xstrcat (in /user/gur27268/Computer_Systems/Socket/DevTest/UTI
==31775==    by 0x804850F: main (in /user/gur27268/Computer_Systems/Socket/DevTest/UTIL/a
==31775==
==31775== LEAK SUMMARY:
==31775==    definitely lost: 14 bytes in 1 blocks.
==31775==    possibly lost:   0 bytes in 0 blocks.
==31775==    still reachable: 0 bytes in 0 blocks.
==31775==         suppressed: 0 bytes in 0 blocks.
==31775== Reachable blocks (those to which a pointer was found) are not shown.**
==31775== To see them, rerun with: --show-reachable=yes

我已经释放了src,但是使用realloc会导致这个问题......

任何帮助将不胜感激..

1 个答案:

答案 0 :(得分:8)

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
}