To avoid memory leaks, we need to handle redistribution with caution (more on this later). Realloc function:
void *realloc(void *ptr, size_t size)where
ptr= pointer to the original memory block ( malloc'ed) and
size= new size of the memory block (in bytes).
realloc ( ) - NULL, ! NULL, , realloc.
( : realloc malloc ( ..), realloc , ):
struct st_temp **temp_struct;
temp_struct = malloc(20 * sizeof *temp_struct);
if (temp_struct == NULL) { }
for (int i = 0; i < 20; ++i) {
temp_struct[i] = malloc(sizeof *temp_struct[i]);
temp_struct[i]->prod = "foo";
}
struct st_temp **tmp;
tmp = realloc(temp_struct, 30 * sizeof *temp_struct);
if (tmp == NULL) {
} else {
temp_struct = tmp;
}
for (int i = 20; i < 30; ++i) {
temp_struct[i] = malloc(sizeof *temp_struct[i]);
temp_struct[i]->prod = "bar";
}
for (int i = 0; i < 30; ++i)
free(temp_struct[i]);
free(temp_struct);
, , - , . 1 ( ).