Search code examples
cdynamic-memory-allocation

How to allocate dynamic memory and reallocate after reallocate how we bring middle freed memory to one block memory


Assume 10k heap

int *p1;
p1 = malloc(3*K); 

Then, a further 4K is requested:

p2 = malloc(4*K);

3K of memory is now free.

Some time later, the first memory allocation, pointed to by p1, is de-allocated:

free(p1);

This leaves 6K of memory free in two 3K chunks. A further request for a 4K allocation is issued:

p1 = malloc(4*K);

This results in a failure – NULL is returned into p1 – because, even though 6K of memory is available, there is not a 4K contiguous block available

How can I merge the two 3K blocks to make a single one of 6K?

the following code giving segmentation error.

if I free 2 and 4 row that freed memory two blocks marge as one block how it possible

#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);
}

Solution

  • You can't defragment the memory, In case if you wanna do it, you cab call me.

    I have already experience this kind of situation, but I don't have the code now yet I am still confident that you cant do this as it is impossible