Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Allocation and Deallocation in C

Tags:

c

I am allocating memory to a void * of some specific size. After allocating I want to show a memory leak and want to deallocate that memory but to some particular size given.

For example : I have allocated memory of 1000bytes using malloc now I want to deallocate 500 bytes of this 1000 bytes.

How can i do that?

Thank you and Regards

like image 352
Akshay Avatar asked Jul 03 '26 20:07

Akshay


1 Answers

There is no way to free just some memory from allocated one. But have option of realloc is attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.

void func()
{
        //allocate 1000 byte
    void *ptr = malloc(1000);

        //reallocate with new size 
    ptr = realloc(ptr ,500);
        //Now you have memory of 500 byte


      //free memory after use
    return;
}
like image 133
Mohan Avatar answered Jul 05 '26 11:07

Mohan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!