I have the following code that creates a directory in C. I tested it multiple times, reviewed it a few times and it looks fine at the moment.
What I really wanna know is what bugs does it have and how can I fix them ? (comparing it with the mkdir
command from linux)
#include "ourhdr.h"
#include <sys/stat.h>
#include <limits.h>
#include <dirent.h>
int main(int argc, char **argv)
{
if(argc != 2)
{
printf("./i78 /locatie/nume_director sau ./i78 nume_director\n");
return 1;
}
char buff[PATH_MAX];
strcpy(buff,argv[1]);
if (mkdir(buff,S_IRWXU|S_IRWXG|S_IRWXO)<0)
{
printf("%s: cannot create directory '%s': File exists\n",argv[0],buff);
}
else
printf("\n Creare director [%s]\n",buff);
}
2 Answers 2
There is a potential buffer overflow - the length of argv[1]
may be up to ARG_MAX
, which is likely larger than PATH_MAX
.
The "File Exists" message may be misleading, mkdir
can also fail because of permissions, out of space, invalid characters in the name, ...
It's good practice to put {
}
around all conditionals, including the else
.
strcpy(buff,argv[1]);
is unnecessary. You may work directly withargv[1]
.The error message is misleading. There are plenty of reasons for
mkdir
to fail, other than "File exists". Useperror
.Do not
#include
files you don't need, in this case<limits.h>
and"ourhdr.h". BTW, what _is_
"ourhdr.h"`?Do not mix languages. The error message is in English, the rest are in Portugese. In the production-grade code, one would use
i18n
.
looks fine [from my perspective]
doesn't quite cut it in my book.) \$\endgroup\$