I am very new to C++. I am facing memory leak issue in my c++ code. Please see the below mentioned piece of code, which is causing the issue.
void a()
{
char buffer[10000];
char error_msg[10000];
char log_file[FILENAME_L] = "error_log.xml";
FILE *f;
f = fopen(log_file,"r");
while (fgets(buffer, 1000, f) != NULL)
{
if (strstr(buffer, " Description: ") != NULL)
{
strcpy(error_msg, buffer);
}
}
fclose(f);
actual_error_msg = trimwhitespace(error_msg);
}
Can anyone please suggest on this. Do I need to use malloc instead of hardcoded size of array?
It seems that there is undefined behaviour if variable
actual_error_msg
is a global variable and functiontrimwhitespace
does not dynamically alocate memory for a copy of error_msgSo when the function finishes its execution pointer
actual_error_msg
will be invalid.I am suggesting to allocate dynamically memory for a copy of
error_msg
within functiontrimwhitespace
. Or if you already do it yourself then check whether the memory is freed in time.:)Take into account that it looks strange that
buffer
is declared with the size equal to10000
while in thefgets
there is used magic number 1000.