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.
realloc() isn't required to copy and a good implementation avoids unnecessary copies. You should really rely on that. (to clarify: for performance reasons, of course. Always assume an implementation may take a copy)
#include <stdlib.h>
#include <stdio.h>
int main()
{
void *test1 = malloc(16);
void *test2 = realloc(test1, 8);
free(test2);
printf("malloc: %x -- realloc: %x\n", test1, test2);
return 0;
}
example output:
malloc: 4779c0 -- realloc: 4779c0
The malloc(3) API doesn't allow this, other than with realloc(3). In common implementations, shrinking with realloc (usually?) won't trigger a copy, and esp. not if the buffer was large.
If you really want to be able to guarantee non-copying, implement your own allocator on top of POSIX mmap(2) / munmap(2). You can unmap part of a mapping without affecting the pages that weren't in the address range given.