2
\$\begingroup\$

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);
}
vnp
58.6k4 gold badges55 silver badges144 bronze badges
asked May 14, 2020 at 7:57
\$\endgroup\$
3
  • \$\begingroup\$ Please state explicitly, in the question, whether or not the code presented works as intended, to the best of your knowledge. (looks fine [from my perspective] doesn't quite cut it in my book.) \$\endgroup\$ Commented May 14, 2020 at 9:02
  • \$\begingroup\$ @greybeard happy ? that was the last problem of the post \$\endgroup\$ Commented May 14, 2020 at 10:09
  • \$\begingroup\$ Fine with me. To be entirely explicit, you could use Potential bugs in unanticipated cases (a wording from the on-topic page). \$\endgroup\$ Commented May 14, 2020 at 18:02

2 Answers 2

1
\$\begingroup\$

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.

answered May 14, 2020 at 19:08
\$\endgroup\$
1
\$\begingroup\$
  • strcpy(buff,argv[1]); is unnecessary. You may work directly with argv[1].

  • The error message is misleading. There are plenty of reasons for mkdir to fail, other than "File exists". Use perror.

  • 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.

answered May 14, 2020 at 19:09
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.