2

Ima trying to debug my code using Valgrind, but I do have some problems w/ the read function.

Here is the Valgrind log :

==4333== Syscall param read(buf) points to unaddressable byte(s)
==4333==     at 0x4F0C600: __read_nocancel (in /lib64/libc-2.18.so)
==4333==     by 0x400AB7: my_read (get_next_line.c:132)
==4333==     by 0x400B6C: get_next_line (tmp.c:25)
==4333==     by 0x400B27: main (get_next_line.c:146)
==4333== Address 0x401000 is not stack'd, malloc'd or (recently) free'd
==4333==
==4333==
==4333== HEAP SUMMARY:
==4333==    in use at exit : 4,106bytes in 1 blocks
==4333==  total heap usage: 1 allocs, 0 frees, 4,106 bytes allocated
==4333==
==4333== 4,106 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4333==    at 0x4C277AB: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==4333==    by 0x400A59: my_read (get_next_line.c:129)
==4333==    by 0x400B6C: get_next_line (tmp.c:25)
==4333==    by 0x400B27: main (get_next_line.c:146)
==4333==
==4333== LEAK SUMMARY:
==4333==    definitely lost: 4,106 bytes in 1 blocks

And here is the code :

int    my_read(int fd)
{
  char *str;
  void *buff;
  int   x;

  str = NULL;
  if ((buff malloc(BUFFER_SIZE + 10)) == NULL)
     return (NULL);
  buff = NULL;
  while ((x = read(fd, buff, BUFFER_SIZE)) > 0) //LINE 132
     str = (str == NULL) ? my_strdup(buff) : my_strcat(buff, str);
  return (str);
}

BUFFER_SIZE is defined at 4096.

I understand the error, but I don't know how to carry this. If you guys could help me fix this up, it would be awesome. Ty.

Xcrowzz
  • 33
  • 1
  • 1
  • 4

1 Answers1

4

The problem is the

buff = NULL;

statement. After you allocate the space for buffer, you're forgetting that and overwriting it with NULL, and then using that when you call read(). Get rid of that statement.

You also need to free(buff); before you return from the function. Otherwise you'll leak memory every time you call my_read().

And since you return a pointer, the function should be declared:

char * my_read(int fd)
Barmar
  • 741,623
  • 53
  • 500
  • 612