I'm creating a function that will pass a directory path as an argument or if it is left blank, prompt the user for an input.
I have set my PATH_MAX=100 and if statements to check if ((strlen(folder path) + strlen(file path)) > PATH_MAX) will ask the user to input again.
However when I was checking that all conditions work (set PATH_MAX=20), if folder path exceeds by itself the PATH_MAX, buffer crashes due to insufficient size (L'Buffer is too small' &&0).
Is there a way to check whether the user exceeds the PATH_MAX beforehand and inform that path is too long, in order to avoid crashing the buffer? Or should i just increase the size of PATH_MAX?
Code:
#define PATH_MAX 100
void CreateFiles(char folder[PATH_MAX])
{
char addrbook[PATH_MAX] = "caf-sorted.txt";
char path[PATH_MAX]="";
if ((strlen(folder)<4))
{
//User inputs directory
printf("Enter New Directory\n(!Do not enter filename!)\n");
if (NULL == fgets(path, sizeof path, stdin))
{//check if fgets fails
if (ferror(stdin))
{
folder="";
perror("fgets() failed");
CreateFiles(folder);
return;
}
}
}
else
memcpy(path, folder, strlen(folder));
path[strcspn(path, "\n\r")] = 0;
if (strlen(addrbook) > 0 && '\\' != path[strlen(path) - 1])
{
if (PATH_MAX < strlen(path))
{
errno = EINVAL;
perror("'path' too long");
folder="";
CreateFiles(folder);
return;
}
strcat(path, "\\");
}
if (PATH_MAX < (strlen(path) + strlen(addrbook)))
{
errno = EINVAL;
perror("'path\\filename' too long");
folder="";
CreateFiles(folder);
return;
}
}
CreateFiles(char folder[PATH_MAX]),foldercould pointer to a string longer thanMAX_PATH- this can failmemcpy(path, folder, strlen(folder));.folderis being checked in main before passing inCreateFiles,if (folder>PATH_MAX){folder="";}path[strlen(path) - 1]is an exploitable hack asstrlen(path)is not guaranteed to be > 0.if (folder>PATH_MAX)compares a pointer to an integer - perhaps you meant some other test? IAC, better thatCreateFiles()stands on its own and does not fail should a pointer to a long string get passed in.