Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Memory Error Debug Assertion Failed

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.

like image 630
Michael Avatar asked Sep 02 '25 16:09

Michael


1 Answers

You are replacing the pointer now with a different one returned by ctime. Then you are trying to free it. So you end up freeing the pointer returned by ctime, 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 ctime directly.

So this should work just fine:

int writeToLog(char* str, enum LOGLEVEL logLevel) {
    if(logFile && logLevel >= level) {
        FILE* log;
        time_t timer = time(NULL);

        const char *now = ctime(&timer);

        size_t length = strlen(now);
        if(now[length - 1] == '\n') {
            now[length - 1] = '\0';
        }
        log = fopen(logFile, "a+");
        if (log == NULL)
            return -1;
        fprintf(log, "%s%s\n", now, str);
        fclose(log);
    }
    return 0;
}

Also note that you make two calls to strlen(now). You should call it once and save the result.

like image 72
Mysticial Avatar answered Sep 05 '25 08:09

Mysticial