Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the safe alternative to realpath()?

Tags:

c++

c

I am working on a program which uses realpath() to get the absolute path of a file. Unfortunately, this function takes a string buffer that is expected to be so large that it is big enough and that's not safe when this application has to run across multiple platforms. Is there a safe version of this function which avoids the buffer overflow issue, perhaps using dynamic memory allocation?

like image 832
dromodel Avatar asked Nov 05 '10 20:11

dromodel


2 Answers

See here for information on safe and portable use of realpath:

http://www.opengroup.org/onlinepubs/9699919799/functions/realpath.html

Basically, modern standards allow you to pass a NULL pointer, and realpath will allocate a buffer of the appropriate length. If you want to be portable to legacy systems which do not support this standard, simply check #ifdef PATH_MAX and use a fixed-size buffer of length PATH_MAX. As far as I know, there are no legacy systems that lack a constant PATH_MAX but which do not support NULL arguments to realpath.

like image 129
R.. GitHub STOP HELPING ICE Avatar answered Sep 20 '22 14:09

R.. GitHub STOP HELPING ICE


From the manpage:

If resolved_path is specified as NULL, then realpath() uses malloc(3) to allocate a buffer of up to PATH_MAX bytes to hold the resolved pathname, and returns a pointer to this buffer. The caller should deallocate this buffer using free(3).buffer using free(3).

So it seems like you can just do this:

char *real_path = realpath(path, NULL);
// use real_path
free(real_path);
like image 26
Evan Teran Avatar answered Sep 19 '22 14:09

Evan Teran