Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using realloc to shrink the allocated memory

Simple question about the realloc function in C: If I use realloc to shrink the memory block that a pointer is pointing to, does the "extra" memory get freed? Or does it need to be freed manually somehow?

For example, if I do

int *myPointer = malloc(100*sizeof(int)); myPointer = realloc(myPointer,50*sizeof(int)); free(myPointer); 

Will I have a memory leak?

like image 969
Moshe Rosenschein Avatar asked Aug 16 '11 12:08

Moshe Rosenschein


People also ask

Can realloc shrink memory?

Using realloc to shrink an allocation is allowed. You can also use realloc to completely release a block of memory by passing 0 as the new size for the block. You can also use realloc to allocate an entirely new block of memory by passing NULL as the address of the block to reallocate.

What is the purpose of realloc ()?

The function realloc is used to resize the memory block which is allocated by malloc or calloc before. Here, pointer − The pointer which is pointing the previously allocated memory block by malloc or calloc. size − The new size of memory block.

Can we decrease size of array using realloc?

Realloc is only for changing the size of dynamically allocated memory. Arryas are statically allocated. Therefore, it's not possible to change Array sizes i.e. the number of elements in an array using realloc function.

How do I Freeocate allocated memory with realloc?

Once you call realloc() , you do not have to free() the memory addressed by pointer passed to realloc() - you have to free() the memory addressed by the pointer realloc() returns. (Unless realloc() returns NULL , in which case the original block of memory - passed to realloc() - has to be free() 'd.)


1 Answers

No, you won't have a memory leak. realloc will simply mark the rest "available" for future malloc operations.

But you still have to free myPointer later on. As an aside, if you use 0 as the size in realloc, it will have the same effect as free on some implementations. As Steve Jessop and R.. said in the comments, you shouldn't rely on it.

like image 113
cnicutar Avatar answered Sep 30 '22 21:09

cnicutar