我正在編寫一個測試動態內存分配的程序,以查看50%的規則有多好。50%規則
該程序有10,000個指針來動態分配內存塊。它還有一個數組來存儲每個塊的大小。它應該:
- 使用
malloc()
動態分配的內存塊的ptrList
每個元素。這些塊應具有在1到10,000個字節範圍內隨機選擇的大小,塊大小應存儲在sizeList
陣列中。 - 初始塊分配後,程序應該反覆釋放塊並分配新塊。這應該循環100,000次迭代。在每次迭代中,隨機選擇
ptrList
中的索引,將塊釋放,然後用具有隨機大小的新動態分配塊替換。 - 每完成100次迭代後,它應該打印出一行顯示迭代計數,近似堆大小(由任何塊中包含的最高和最低內存地址之間的差異確定)以及所有塊的總大小由
ptrList
指向的塊。
我有我的程序編碼,像這樣:
#include <stdio.h>
#include <pthread.h> /* for pthreads */
#include <stdlib.h> /* for exit */
/** Number of memory blocks to allocate/deallocate. */
#define BLOCK_COUNT 10000
/** Number of free/malloc operations to perform */
#define TEST_LENGTH 100000
/** Maximum size of an allocated block. */
#define SIZE_LIMIT 10000
int main(int argc, char *argv[]) {
// Array of pointers to all blocks that have been allocated.
char *ptrList[ BLOCK_COUNT ];
// Array of sizes for each block, so we can know how much memory we're using.
int sizeList[ BLOCK_COUNT ];
// Insert your code here
for (int j = 0; j < 1000; j++) {
int minimum = 0;
int maximum = 0;
int total = 0, remainder = 0;
for (int i = 0; i < BLOCK_COUNT; i++) {
int size = (rand() % SIZE_LIMIT) + 1;
ptrList[i] = malloc (size);
sizeList[i] = size;
total += size;
int heapsize = (int)ptrList[i];
if (i == 0) {
maximum = heapsize;
minimum = heapsize;
}
else {
if (heapsize > maximum) {
maximum = heapsize;
}
if (heapsize < minimum) {
minimum = heapsize;
}
}
}
for (int i = 0; i < TEST_LENGTH; i++) {
int index = rand() % BLOCK_COUNT;
int size = (rand() % SIZE_LIMIT) + 1;
free(ptrList[index]);
total -= sizeList[index];
ptrList[index] = malloc (size);
sizeList[index] = size;
total += sizeList[index];
int heapsize = (int)ptrList[index];
if (heapsize > maximum) {
maximum = heapsize;
}
if (heapsize < minimum) {
minimum = heapsize;
}
}
if (j > 0) {
remainder = j % 100;
}
if (remainder == 0) {
//printf("%d", example);
printf("%d %d %d\n", j, maximum - minimum, total);
}
for (int i = 0; i < BLOCK_COUNT; i++) {
free(ptrList[i]);
}
}
return 0;
}
很接近我的內存分配/釋放的正確方法?在我執行for
循環之前,我的程序編譯並運行(沒有輸出),其中int j
。它在我實現它之後掛起,所以也許有人可以幫我把問題固定在那裏。
編輯: 50%的規則是所有塊的總大小除以堆大小的近似值一般將在50%左右。
「它在我實現它之後掛起」 - 這通常被認爲是一個問題... –
@MitchWheat是的,我不太確定是什麼導致它。註釋掉for(int j = 0; j <1000; j ++)'允許程序運行完成。只要我重新註釋該行,程序就會掛起。我也嘗試在每次迭代結束時添加一個for循環來釋放內存。 – raphnguyen
正如FYI一樣,隨機分配和釋放歷史上一直是程序內存使用的非常糟糕的模型。從這樣的實驗中可以得出很多可靠的結論。通過將分配器替換爲幾個大的進程(如Web瀏覽器(連續運行)或編譯器(在處理文件後結束)),您可能會獲得更多有趣的數據。 –