I am working on a project and I have to increase the size of an array or it prints garbage.
This variable is declared in main
char *fullPath[150];
Then I ask a user a question using this
printf("Enter full path where you want the file to be.\nExample: C:\\Windows\\System32\n");
scanf("%s", &fullPath);
Then I check that this directory exists using
CheckDirectory(fullPath);
Which is my function that looks like...
void CheckDirectory(char *d) {
DIR* dir = opendir(d);
char answer[2];
if (dir) {
printf("Directory Exists!\n");
closedir(dir);
} else if (ENOENT == errno) {
printf("Directory does not exist.\n");
printf("Do you want to create this directory? y/n:");
scanf("%s", &answer);
if (strcmp(answer, "y") == 0) {
printf("Ok creating directory\n");
MakeDirectory(d);
} else {
printf("ok not gonna make it");
exit(1);
}
} else {
printf("Some magical error.");
}
}
So the above code just basically asks a user for a directory and then puts it into fullPath[150] and then runs tests on it. The next part of the script which is where I run into errors is..
CopyNewFile(fullPath, fileName, argv[0]);
An the function looks like..
void CopyNewFile(char *dir, char *fname, char *curName) {
char fullDir[350];
char file[60];
strncat(file, curName, 20);
strncat(file, ".exe", 5);
strncat(fullDir, dir, 250);
strncat(fullDir, "\\", 5);
strncat(fullDir, fname, 30);
if (CopyFile(file, fullDir, FALSE)) {
printf("\n\nCopied new file.\n\n");
} else {
printf("Did not copy.");
};
}
Now, here is the issue. When I try to run this, it won't copy unless
char fullDir[350];
Is more than 300. I tried 350 and it works, but I haven't tested to find the exact number where it does and does not work. If I it 300, then the fullDir and file gets garbage characters in front of it.
I assume it is something to do with the way memory is allocated but instead of increasing the size of the character arrays I would like to fix it.