开发者

Valgrind complains while using realloc functions?

开发者 https://www.devze.com 2023-02-16 07:50 出处:网络
I have implemented my own version of strcat function. It works fine but valgrind complains. main() { char *src=NULL;

I have implemented my own version of strcat function.

It works fine but valgrind complains.

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 ERROR :

==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=ye开发者_开发知识库s

I have freed src, but using realloc tends to this problem...

Any help would be appreciated..


void xstrcat(char *src,const char *dest) {

You're passing src by value, and xstrcat is working on and modifying its local copy. Any changes you make to src will not be reflected in the calling function.

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

...
xstrcat(&src, ...)

This approach lets xstrcat modify main's src variable.

To quote a frequently mentioned sample:

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消