Reputation: 9
I'm new to C programming and I've been having a issue in one of my functions which is supposed to get the characters in a char array.
This is my code:
int main()
{
char javaFileLocation[512];
char cFileLocation[512];
char cFileName[512];
printf("Type in the location of the Java file you'd like to convert : \n\n");
fgets(javaFileLocation, 512, stdin);
removeLastChar(javaFileLocation);
printf("Choose the location you want the resulting C file to be in : \n\n");
fgets(cFileLocation, 512, stdin);
removeLastChar(cFileLocation);
printf("Choose the name for the new C file : \n\n");
fgets(cFileName, 512, stdin);
removeLastChar(cFileName);
FILE * javaFile = fopen(javaFileLocation, "r");
if(javaFile == NULL) {
printf("The java file you specified does not exist!: ");
perror("fopen error: ");
return 1;
}
strcat(cFileLocation, cFileName);
FILE * cFile = fopen(cFileLocation, "w");
if(cFile == NULL) {
printf("The c file was not able to be created!: ");
perror("fopen error: ");
return 1;
}
printf("file has been successfully created. \n");
int maxSize = 0;
char contents[512];
while (fgets(contents, sizeof(contents), javaFile)) {
maxSize = maxSize + strlen(contents) + 1;
}
char translated[maxSize];
rewind(javaFile);
while (fgets(contents, sizeof(contents), javaFile)) {
getTranslation(contents, translated);
}
fprintf(cFile, translated);
fclose(javaFile);
fclose(cFile);
return 0;
}
void removeLastChar(char * word){
word[strlen(word) - 1] = '\0';
}
void getTranslation(char line[], char translation[]){
char current[strlen(line)];
int index;
for(index = 0; index < strlen(line); index++){
strcat(translation, line[index + 1]);
}
}
My issue is happening in getTranslation and is the line strcat(translation, line[index + 1]);
. The code runs, but when it reaches that line, the program freezes, does nothing, and I get this as the return code in my console:
Process returned -1073741819 (0xC0000005) execution time : 24.007 s
If anyone knows what's wrong and can help me it'd be greatly appreciated.
Upvotes: 0
Views: 59
Reputation: 121609
On Windows, (0xC0000005) is an access violation.
This is Bad. It means you're writing outside "legal" memory. It will crash your program.
Among other things, I would modify getTranslation() to ensure that, however often you append (strcat) to "translated", you NEVER exceed 511 characters (remember - you always need to reserve an extra byte for the null termination character).
Upvotes: 1
Reputation: 378
Your index
goes from 0 to strlen(line)
, but since you are adding +1 you are effectivelly iterating from 1 to strlen(line)
, and thus the last iteration will fail when it tries to access line[strlen(line)+1]
. But there is a more important issue which has already been pointed out in the comments: strcat takes a const char*
as the second argument, but you are passing a char
. Does your code even compile?
Upvotes: 0