Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, free half of the memory chunk, without freeing the other half

Tags:

c

malloc

free

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).

like image 644
VikasPushkar Avatar asked Dec 15 '22 13:12

VikasPushkar


1 Answers

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.

like image 132
Sourav Ghosh Avatar answered Dec 28 '22 06:12

Sourav Ghosh