I am getting the following error when running my program.
Debug Assertion Failed!
File: f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c
Line: 1322
Expression: _CrtIsValidHeapPointer(pUserData)
So I debugged my program and found out that the problem occurred when the following function was called the second time, more specifically the free statement at the end.
int writeToLog(char* str, enum LOGLEVEL logLevel) {
if(logFile && logLevel >= level) {
FILE* log;
char *now = (char *)malloc(sizeof(char)*1024);
time_t timer = time(NULL);
if(*now == NULL) {
return -1;
}
now = ctime(&timer);
if(now[strlen(now) - 1] == '\n') {
now[strlen(now) - 1] = '\0';
}
log = fopen(logFile, "a+");
if (log == NULL)
return -1;
fprintf(log, "%s%s\n", now, str);
fclose(log);
free(now); //fails here on the second function call
}
return 0;
}
Now I would love to just make now a constant char array but visual studio isn’t letting me do that because of the return type of ctime. Can anyone help?
Cheers.
You are replacing the pointer
nowwith a different one returned byctime. Then you are trying to free it. So you end up freeing the pointer returned byctime, and not the pointer you allocated yourself.You are not supposed to modify the pointer returned by
ctime.For your purposes, you don’t even need to allocate any memory at all. You can just use the pointer returned by
ctimedirectly.So this should work just fine:
Also note that you make two calls to
strlen(now). You should call it once and save the result.