I have a function that adds a directory to a defined path, more or less, exactly as the "cd-function" in the command prompt. The first time I add a directory everything works perfectly, the second or third time (depends on the length of the directory) the program crashes.
char path[PATH_MAX];
void dir_forward(char cmd[])
{
char *temp = malloc(strlen(path) + strlen(cmd) + 2);
char sep[] = "\\";
strcpy(temp, path); // copy path to temp
strcat(temp, sep);
strcat(temp, cmd+3); // +3 for removing "cd " from string
int i = strlen(temp); // add null terminator
temp[i] = '\0';
strcpy(path, temp);
free(temp);
printf("%s\n", path);
}
The program first copies the path to a temporary variable (the size of the temporary variable is determined as the size of the path, the new directory, one backslash, and a null terminator). After that, the backslash and the new directory gets copied to the path in the temporary variable. A null terminator is appended to the end of the string. After that, the new path in the temporary variable gets copied to the path and thus replaces the old one.
Let me demonstrate with an example, I have:
C:\Users\Paul\Desktop\some_folder
I decided to append the folder "images" to the path:
C:\Users\Paul\Desktop\some_folder\images
If I append one more folder (preferably with a long name) the program will crash almost like a buffer overflow and also end the path with some weird characters.
[EDIT]
I cannot reproduce the code completely since its rather large, however, below is the essence of the function. First, the program adds a path to the variable path with the help of getcwd(), after that accepts an input and sends it to the function above.
int main(void)
{
char cmd[30];
getcwd(path, PATH_MAX); // Get current path
scanf("%s", cmd);
dir_forward(cmd);
}
This should be enough to reproduce the problem I guess.