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'.
getting heap corruption detected when freeing memory with calloc and changed stdout [duplicate]
-
04-06-2022 - |
Question
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 ?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow