C 内存错误调试断言失败

标签 c visual-studio debugging memory free

运行程序时出现以下错误。

调试断言失败!
文件:f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c
线路:1322
表达式:_CrtIsValidHeapPointer(pUserData)

所以我调试了我的程序,发现问题发生在第二次调用以下函数时,更具体地说是最后的 free 语句。

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 设为常量字符数组,但 Visual Studio 不允许我这样做,因为 ctime 的返回类型。有人可以帮忙吗?
干杯。

最佳答案

您正在将now 指针替换为ctime 返回的另一个指针。然后你试图释放它。因此,您最终释放了 ctime 返回的指针,而不是您自己分配的指针。

您不应该修改 ctime 返回的指针。

出于您的目的,您甚至根本不需要分配任何内存。您可以直接使用ctime返回的指针。

所以这应该可以正常工作:

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;
}

另请注意,您对 strlen(now) 进行了两次调用。您应该调用一次并保存结果。

关于C 内存错误调试断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7788557/

相关文章:

iphone - ! vs == nil 在 objective-c

c++ - 创建 DLL 时导出所有符号

visual-studio - Visual Studio 宏中的宏扩展或添加

c# - Windbg .load 扩展需要路径中的转义反斜杠 (\) 字符

c# - 带有远程设备的控制台 Windows Phone 8

c - 如何以二进制形式表示地址 0x80 到 1<<31

c - 给定 k 组整数,找到所选 k 个元素之间的最小差异

javascript - chrome 替代 firebug 的评估控制台?

比较结构体中字符串的第一个字母

c# - 当我运行所有测试时单元测试失败,但当我调试时单元测试通过