0

I am trying to change the stdout into a file, write something and than retrun it back to screen. My code is :

FILE *stream ;
char * file_name = "LRA_SOLVER";
char * file_ext = ".txt";
char file_number [3] = {0};
itoa (lra_solver_couter++,file_number,10);
char* file_full_name = (char*)calloc(strlen(file_number)+10+4,sizeof(char));
strcpy(file_full_name, file_name);
strcat(file_full_name, file_number);
strcat(file_full_name, file_ext); 
if((stream = freopen(file_full_name, "w", stdout)) == NULL)
    exit(-1);
print(); // a lot of printing into the file.
stream = freopen("CON", "w", stdout); // change it back
free(file_full_name);

but I am getting the error heap corruption detected... the lra_solver_couter isn't big (usually 0-20). What am I doing wrong ?

Lundin
  • 195,001
  • 40
  • 254
  • 396
yehudahs
  • 2,488
  • 8
  • 34
  • 54
  • 1
    Quite often when you get "heap corruption", it is ANOTHER object that either was freed earlier, or allocated later, that causes the problem, not the actual object being freed. – Mats Petersson Jul 24 '13 at 11:55
  • You could prove that by using a stack-based string variable (I would do that anyway, as filenames are typically fairly limited in size, so `char file_full_name[PATH_MAX];` should work for any sane path). – Mats Petersson Jul 24 '13 at 11:57
  • why you use `stream = freopen("CON", "w", stdout); // change it back` ? – Grijesh Chauhan Jul 24 '13 at 11:58
  • Have you tried running this code with valgrind? – arne Jul 24 '13 at 11:59
  • @arne: Does valgrind work on Windows? Since when? – Mats Petersson Jul 24 '13 at 12:02
  • @MatsPetersson I don't think there's a windows version yet, although http://sourceforge.net/p/valgrind4win/wiki/ProjectStatus/ looks a little promising. OP didn't state windows though, hence I suggested valgrind. – arne Jul 24 '13 at 12:07
  • Now when digging up old post like this to edit, maybe check: Is it otherwise correctly tagged? Is it a super common FAQ that could as well just be dupe hammered? – Lundin Aug 10 '21 at 14:35

1 Answers1

1

You forgot the terminating '\0' when you calculate the needed length of file_full_name: You only have strlen(file_number)+10+4 with 10 == strlen(file_name) and 4 == strlen(file_ext). Add 1 for `\0'.

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33