Syscall param getcwd(buf) points to unaddressable byte(s)

78 views Asked by At

I am testing a program using valgrind for the first time. I haven't found any help regarding this error. What am I doing wrong? how do I solve it?

Minimal reproducible example:

#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>


int main(){
   char* dir = "testdir";
   mkdir(dir,0777);
   char* buf = calloc(1, sizeof(char)*255);
   char* directory = realpath(dir, buf);
   printf("%s\n", directory);
   free(buf);
}

The valgrind report:

==18518== Syscall param getcwd(buf) points to unaddressable byte(s)
==18518==    at 0x4969AF2: getcwd (getcwd.c:78)
==18518==    by 0x48AD520: realpath@@GLIBC_2.3 (canonicalize.c:88)
==18518==    by 0x109216: main (in /home/sol/Documents/SOLProject/.test/a.out)
==18518==  Address 0x4a5013f is 0 bytes after a block of size 255 alloc'd
==18518==    at 0x483DD99: calloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==18518==    by 0x1091FF: main (in /home/sol/Documents/SOLProject/.test/a.out)
==18518== 
/home/sol/Documents/SOLProject/.test/testdir
==18518== 
==18518== HEAP SUMMARY:
==18518==     in use at exit: 0 bytes in 0 blocks
==18518==   total heap usage: 2 allocs, 2 frees, 1,279 bytes allocated
==18518== 
==18518== All heap blocks were freed -- no leaks are possible
==18518== 
==18518== For lists of detected and suppressed errors, rerun with: -s
==18518== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

1

There are 1 answers

0
Paul Floyd On

Using hot-off-the-press Valgrind 3.22 on FreeBSD 13.2 I get

==12420== Syscall param __realpathat(buf) points to unaddressable byte(s)
==12420==    at 0x4994B1A: ??? (in /lib/libc.so.7)
==12420==    by 0x49CDC16: realpath (in /lib/libc.so.7)
==12420==    by 0x2019D3: main (so12.c:10)
==12420==  Address 0x545f13f is 0 bytes after a block of size 255 alloc'd
==12420==    at 0x4851725: calloc (vg_replace_malloc.c:1599)
==12420==    by 0x2019C2: main (so12.c:9)

As mentioned in the comments, realpath expects

The resolved_path argument must point to a buffer capable of storing at
least PATH_MAX characters, or be NULL.

If I change realpath to take NULL for the buffer

#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>


int main(){
   char* dir = "testdir";
   mkdir(dir,0777);
   char* directory = realpath(dir, NULL);
   printf("%s\n", directory);
   free(directory);
}

then I get no error.