2

What should i fill in the second parameter of the function getcwd if I am reading the current directory?

lital maatuk
  • 5,921
  • 20
  • 57
  • 79

2 Answers2

4

The size of the buffer you want to fill:

char result[PATH_MAX];
char *r = getcwd(result, PATH_MAX);

Failure to set this correctly (or spot ENAMETOOLONG/ERANGE) could lead to buffer overflow problems.

Caveat: Not all platforms provide PATH_MAX. If you can be sure it's there on your platforms it is quite handy.

You can also use realpath(), (POSIX.1-2008) which will malloc() memory for you to do this more cleanly:

char *result = realpath(".", NULL);
// do stuff with result
free(result);
Flexo
  • 87,323
  • 22
  • 191
  • 272
  • Shouldn't it be `PATH_MAX-1` to take care of the terminating null character? – Ambareesh May 06 '22 at 16:19
  • I don't believe so, the manpage states "If the length of the absolute pathname of the current working directory, including the terminating null byte, exceeds size bytes, NULL is returned," – Flexo May 07 '22 at 12:44
2

The length of the buffer you provide in the first parameter, so that overflow cannot occur.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157