Akshay
Akshay

Reputation: 85

Memory Allocation and Deallocation in 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

Upvotes: 3

Views: 907

Answers (2)

Mohan
Mohan

Reputation: 1901

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

Upvotes: 3

Gopi
Gopi

Reputation: 19864

There is no way to deallocate just 500 bytes out of 1000bytes allocated.

free() function takes pointer returned by only malloc() and its family functions for allocation. So it will free all the memory allocated.

If your purpose is to show memory leak then

void func()
{
  void *p =  malloc(1000);
  // Some stuff
  return;
}

Memory allocated is not freed here and you have a memory leak.

Upvotes: 1

Related Questions