Valgrind жалуется при использовании функций realloc? - PullRequest
2 голосов
/ 13 марта 2011

Я реализовал свою собственную версию функции strcat.
Работает нормально, но жалуется Вальгринд.

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

ОШИБКА ВАЛЬГРИНДА:

==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 Ответ

8 голосов
/ 13 марта 2011
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
}
...