Skip to main content
 首页 » 编程设计

crash之rapidJson:在 Release模式下崩溃

2025年05月04日119haluo1

我用了rapidJson读取json数据。我可以在调试和 Release模式下构建我的应用程序,但应用程序在 Release模式下崩溃。

    using namespace rapidjson; 
    ... 
    char *buffer; 
    long fileSize; 
    size_t fileReadingResult; 
 
    //obtain file size 
    fseek(pFile, 0, SEEK_END); 
    fileSize = ftell(pFile); 
    if (fileSize <= 0) return false; 
    rewind(pFile); 
 
    //allocate memory to contain the whole file 
    buffer = (char *)malloc(sizeof(char)*fileSize); 
    if (buffer == NULL) return false; 
 
    //copy the file into the buffer 
    fileReadingResult = fread(buffer, 1, fileSize, pFile); 
    if (fileReadingResult != fileSize) return false; 
    buffer[fileSize] = 0; 
 
    Document document; 
    document.Parse(buffer); 

当我在 Release模式下运行它时,我遇到了 Unhanded exception; A heap has been corrupted .
应用程序在 "res = _heap_alloc(size) 处中断在 malloc.c文件
void * __cdecl _malloc_base (size_t size) 
{ 
     void *res = NULL; 
 
//  validate size 
if (size <= _HEAP_MAXREQ) { 
    for (;;) { 
 
        //  allocate memory block 
        res = _heap_alloc(size); 
 
        //  if successful allocation, return pointer to memory 
        //  if new handling turned off altogether, return NULL 
 
        if (res != NULL) 
        { 
            break; 
        } 
        if (_newmode == 0) 
        { 
            errno = ENOMEM; 
            break; 
        } 
 
        //  call installed new handler 
        if (!_callnewh(size)) 
            break; 
 
        //  new handler was successful -- try to allocate again 
    }   

它在 Debug模式下运行良好。

请您参考如下方法:

也许它可能是 memory leak您的 Malloc 的问题因为它在 Debug 中运行良好一次,但是当您将应用程序保持更长的时间时,它会崩溃。

你有吗free您的 buffer使用后?