void BinaryInput::readBytes(void* bytes, int64 n) { prepareToRead(n); debugAssert(isValidPointer(bytes)); memcpy(bytes, buffer + pos, n); pos += n; }
/* * Function: my_realloc * * Purpose: emulate realloc plus check memory allocation for debug. */ void* my_realloc(void* ptr, size_t size, char* file, int line) { char* newptr; reallocscalled++; if (!isValidPointer(ptr, file, line)) { printf("\nrealloc MEM overwrite: FILE %s LINE %d\n[mallocs %ld] [frees %ld] [reallocs %ld]\n", file, line, mallocscalled, freescalled, reallocscalled); exit(1); } newptr = ((char*)ptr) - sizeof(BYTE2) - sizeof(size_t); newptr = realloc(newptr, size + kExtraBytes); if (newptr) { // start signiture *((BYTE2*)newptr) = kStartSigniture; newptr += sizeof(BYTE2); // store length of ptr memcpy(newptr, &size, sizeof(size_t)); newptr += sizeof(size_t); // end signiture *((BYTE4*)&newptr[size]) = kEndSigniture; } return newptr; }
/* * Function: my_free * Purpose: emulate free plus check memory allocation for debug. */ void my_free(void* ptr, char*file, int line) { char* newptr; size_t ptrsize; freescalled++; if (!isValidPointer(ptr, file, line)) { printf("\nfree MEM overwrite: FILE %s LINE %d\n[mallocs %ld] [frees %ld] [reallocs %ld]\n", file, line, mallocscalled, freescalled, reallocscalled); exit(1); } newptr = ((char*)ptr) - sizeof(BYTE2) - sizeof(size_t); // real start ptrsize = *((size_t*)&newptr[sizeof(BYTE2)]); // size of pointer memset(ptr, 0xFF, ptrsize); // make sure mem is changed free(newptr); return; }
void free(void* ptr) { if (ptr == NULL) { // Free does nothing on null pointers return; } debugAssert(isValidPointer(ptr)); if (inTinyHeap(ptr)) { lock(); tinyFree(ptr); unlock(); return; } uint32 bytes = ((uint32*)ptr)[-1]; lock(); if (bytes <= smallBufferSize) { if (smallPoolSize < maxSmallBuffers) { smallPool[smallPoolSize] = MemBlock(ptr, bytes); ++smallPoolSize; unlock(); return; } } else if (bytes <= medBufferSize) { if (medPoolSize < maxMedBuffers) { medPool[medPoolSize] = MemBlock(ptr, bytes); ++medPoolSize; unlock(); return; } } bytesAllocated -= bytes + 4; unlock(); // Free; the buffer pools are full or this is too big to store. ::free((uint8*)ptr - 4); }