I'm writing a function in C which adds a new product entry to an array of structs. The array is defined in the following structure:
struct product_array {
struct product *arr;
unsigned int count; //Initially set to NULL, counts the number of entries
};
The array is dynamically allocated, but each time a new entry is added it should be reallocated. Each element of an array consists of product structure:
struct product {
char *title;
char code[8]; // Should be truncated to 7 characters
};
This is what I wrote:
void add_product(struct product_array *pa, const char *title, const char *code)
{
pa->arr = realloc(pa->arr, sizeof(struct product) * (pa->count + 1));
if (pa->arr == NULL)
return NULL;
char *temp = malloc(strlen(title) + 1); // for title memory
//should be dynamically allocated separately
if (temp == NULL){
return NULL;
}
memmove(temp, title, (strlen(title) + 1));
title = temp;
pa->arr[pa->count].title = title;
int j = 0;
while (*code) {
pa->arr[pa->count].code[j] = (*code);
code++;
j++;
if (j == 7)
break;
}
pa->arr[pa->count].code[j] = '\0';
pa->count++;
}
It seems to work fine (though I'm not sure if I used realloc correctly). But now I'm supposed to release the memory. I did it by writing:
free(pa->arr);
It also seems to be okay. But now I'm supposed to release memory which was allocated for title. To do that I should change main.c.
int main()
{
struct product_array pa;
pa.count = 0;
pa.arr = NULL;
add_product(&pa, "Product 1", "1111");
add_product(&pa, "Product 2", "123320");
add_product(&pa, "Product 3", "565496845");
}
And here I'm lost.
free (pa.arr->title);
doesn't seem to work.
Would really appreciate your help.