If I have allocated a memory chunk say
char *a =(char*)malloc(sizeof(char)*10);
and I do
strcpy( "string of len 5",a);
then is there a way to free the left over part of my memory chunk?
In other scenario if I do
strcpy("string of len5", (a+5));
then first half will be empty. is there a way to free()
that first part without deallocating the second half?
Please don't suggest realloc()
as it allocates a new chunk of memory copy content there and release the previous.(AKAIK).
No, there is no way you can free()
half or part of the dynamically allocated memory. You need to free()
it all at a time.
While getting the memory through dynamic memory allocation, you basically get a pointer. You need to pass the exact pointer to free()
. Passing a pointer to free()
which is not returned by malloc()
or family, is undefined behaviour.
FYI, see this related answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With