【发布时间】:2017-09-15 16:32:16
【问题描述】:
假设 10k 堆
int *p1;
p1 = malloc(3*K);
然后,请求进一步的 4K:
p2 = malloc(4*K);
现在有 3K 内存可用。
一段时间后,由 p1 指向的第一个内存分配被取消分配:
free(p1);
这会在两个 3K 块中留下 6K 的可用内存。发出进一步的 4K 分配请求:
p1 = malloc(4*K);
这会导致失败 - NULL 被返回到 p1 - 因为,即使 6K 的内存可用,也没有 4K 的连续块可用
如何将两个 3K 块合并为一个 6K 块?
以下代码给出分段错误。
如果我释放了释放内存的 2 和 4 行,那么这两个块将成为一个块,这怎么可能
#include<stdio.h>
#include<stdlib.h>
int** allocate2D(int rows,int cols)
{
int **arr2D;
int i;
arr2D = (int**)malloc(rows*sizeof(int*));
for(i=0;i<rows;i++)
{
arr2D[i] = (int*)malloc(cols*sizeof(int));
}
}
void deallocate2D(int** arr2D,int rows)
{
int i,a,b;
printf("Enter from which row you want to delete");
scanf("%d",&a);
printf("Enter till which row you want to delete");
scanf("%d",&b);
for(i=a;i<b;i++)
{
free(arr2D[i]);
}
}
main( )
{
int i,j,k;
int **arr2D;
arr2D=allocate2D(5,5);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
scanf("%d" ,arr2D[i][j]);
}
}
deallocate2D(arr2D,k);
}
【问题讨论】:
-
我以前(几天前)见过这个问题。答案是:你不能。
-
从应用程序的角度来看,您不能“合并”块,因为您无法控制分配器。如果你想要这种能力,你必须创建自己的分配器。
-
@Someprogrammerdude 我们如何创建自己的内存分配器?
-
@praneeth 编写一些代码来分配和释放内存
标签: c dynamic-memory-allocation