When my program gets to the return 0 in main the program exits, but control does not return to the command line. I have even tried exit(), to no avail. Any suggestions
int main (int argc, char* argv[])
{
char name[100];
char reg[200];
char replace[200];
if(argc==3){
strcpy(reg, ".*");
strcat(reg, argv[1]);
strcat(reg, ".*");
}
else if(argc==4){
strcpy(reg, "\\(\\(.*");
strcat(reg, argv[3]);
strcat(reg, ".*");
strcat(reg, argv[1]);
strcat(reg, ".*\\)\\|\\(.*");
strcat(reg, argv[1]);
strcat(reg, ".*");
strcat(reg, argv[3]);
strcat(reg, ".*\\)\\)");
printf("\n%s\n", reg);
// exit(1);
}
printf("\n%s\n", reg);
strcpy(name, argv[1]);
strcpy(replace, argv[2]);
printf("\n%s\n", name);
// puts(realpath("./b/test2",NULL));
int reti;
char msgbuf[100];
regex_t regex;
/* Compile regular expression */
reti = regcomp(®ex, reg, 0);
if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }
list_dir (".", regex, name, replace);
char line[BUFSIZ];
FILE *fp2=fopen("source.dat","r");
if(fp2==NULL)
printf("Problm opening: source.dat");
FILE *fp3=fopen("result.dat", "r");
if(fp3==NULL)
printf("Problm opening: result.dat");
char line2[1000];
int len;
while( (fgets(line2, BUFSIZ, fp2) != NULL) && (fgets(line, BUFSIZ, fp3) != NULL)) {
len=strlen(line);
if( line[len-1] == '\n' )
line[len-1] = '\0';
len=strlen(line2);
if( line2[len-1] == '\n' )
line2[len-1] = '\0';
rename(line, line2);
}
close(fp2);
free(fp2);
close(fp3);
free(fp3);
remove("source.dat");
remove("result.dat");
regfree(®ex);
return 0;
}
My program does what I intend it to do, but when it finishes the while loop and frees everything, control does not go back to command line without pressing ctr-C. Still stumped on why.
Well, it’s hard to say without a complete program. Based on the code that’s presented, the most obvious bug that jumps out is the file handle usage. The API works like this: you allocate a FILE* by calling fopen(), you deallocate it by calling fclose(). Instead, you are calling close() on a FILE* and then (!) passing it to free().
I’m not sure what exact language/version you’re using, but probably your compiler could have helped you find this problem if you had asked for more error checking. For example, gcc with -Wall would warn that it had to use implicit declarations for close(), free(), etc. After adding in the correct header files (so it can see the prototype declarations for the functions you’re using), it would then say things like:
giving you a clue that you’re using close() incorrectly.