Index: src/vdbesort.c ================================================================== --- src/vdbesort.c +++ src/vdbesort.c @@ -1044,11 +1044,10 @@ SorterMerger *pMerger, int *pbEof ){ int rc; int iPrev = pMerger->aTree[1];/* Index of iterator to advance */ - int i; /* Index of aTree[] to recalculate */ /* Advance the current iterator */ rc = vdbeSorterIterNext(&pMerger->aIter[iPrev]); /* Update contents of aTree[] */ @@ -1279,15 +1278,18 @@ } if( bUseFg==0 ){ /* Launch a background thread for this operation */ void *pCtx = (void*)pThread; - if( pSorter->aMemory==0 ){ - pSorter->aMemory = sqlite3Malloc(pSorter->nMemory); - if( pSorter->aMemory==0 ) return SQLITE_NOMEM; - }else{ - pSorter->nMemory = sqlite3MallocSize(pSorter->aMemory); + assert( pSorter->aMemory==0 || pThread->aListMemory==0 ); + if( pThread->aListMemory ){ + if( pSorter->aMemory==0 ){ + pSorter->aMemory = sqlite3Malloc(pSorter->nMemory); + if( pSorter->aMemory==0 ) return SQLITE_NOMEM; + }else{ + pSorter->nMemory = sqlite3MallocSize(pSorter->aMemory); + } } rc = sqlite3ThreadCreate(&pThread->pThread, vdbeSorterThreadMain, pCtx); }else{ /* Use the foreground thread for this operation */ u8 *aMem; @@ -1335,23 +1337,25 @@ ** * The total memory allocated for the in-memory list is greater ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true. */ nReq = pVal->n + sizeof(SorterRecord); nPMA = pVal->n + sqlite3VarintLen(pVal->n); - if( pSorter->aMemory ){ - bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize; - }else{ - bFlush = ( - (pSorter->nInMemory > pSorter->mxPmaSize) - || (pSorter->nInMemory > pSorter->mnPmaSize && sqlite3HeapNearlyFull()) - ); - } - if( bFlush ){ - rc = vdbeSorterFlushPMA(db, pCsr, 0); - pSorter->nInMemory = 0; - pSorter->iMemory = 0; - assert( rc!=SQLITE_OK || pSorter->pRecord==0 ); + if( pSorter->mxPmaSize ){ + if( pSorter->aMemory ){ + bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize; + }else{ + bFlush = ( + (pSorter->nInMemory > pSorter->mxPmaSize) + || (pSorter->nInMemory > pSorter->mnPmaSize && sqlite3HeapNearlyFull()) + ); + } + if( bFlush ){ + rc = vdbeSorterFlushPMA(db, pCsr, 0); + pSorter->nInMemory = 0; + pSorter->iMemory = 0; + assert( rc!=SQLITE_OK || pSorter->pRecord==0 ); + } } pSorter->nInMemory += nPMA; if( pSorter->aMemory ){ @@ -1373,11 +1377,11 @@ pNew = (SorterRecord*)&pSorter->aMemory[pSorter->iMemory]; pSorter->iMemory += ROUND8(nReq); pNew->u.iNext = (u8*)(pSorter->pRecord) - pSorter->aMemory; }else{ - pNew = (SorterRecord *)sqlite3Malloc(pVal->n+sizeof(SorterRecord)); + pNew = (SorterRecord *)sqlite3Malloc(nReq); if( pNew==0 ){ return SQLITE_NOMEM; } pNew->u.pNext = pSorter->pRecord; }