c - Can I free only a part of a string? -
i filling string of characters , double size time time.
when finish, free unused memory.
void fun (char **str, size_t *len) { size_t lsi; //last_significant_index //filling str , reallocating time time. //*len storing total size of allocated memory @ point // idea #1 free((*str)[lsi + 1]); // idea #2 for(size_t = lsi + 1; < *len; i++) { free(&(*str)[i]); } }
none of these ideas seem work however
is possible it? if so, how?
details:
i using function reallocate strings:
static void increase_list_size(char **list, size_t *list_len) { size_t new_list_size = (*list_len + 1) * 2; // not allocating list @ declaration, *list_len equals 0. char *new_list = malloc(sizeof(char) * new_list_size); (size_t = 0; < *list_len; i++) { new_list[i] = (*list)[i]; } if (list != null) // don't want free empty list (it wasn't allocated @ declaration! { free(*list); } (*list) = new_list; *list_len = new_list_size; }
as can see, allocating two-times more memory every time - that's why wanted free unused memory @ end.
i thought there kind of tricky way it, since felt can use free()
free whole memory block.
no, can free()
pointers have been returned malloc()
.
you want use realloc()
change allocated memory size smaller (as larger) size. contents of array preserved.
example:
#include <stdlib.h> int main() { char *str = malloc(100); ... str = realloc(str, 50); ... free(str); }
remember check return value of realloc()
(as 1 of malloc()
) ensure (re)allocation has not failed.
Comments
Post a Comment