J
J
julien_sorel2015-04-08 16:23:20
C++ / C#
julien_sorel, 2015-04-08 16:23:20

How to free memory in an array of structures in C?

I apologize in advance if some words sound crooked, as I am learning programming from foreign resources and do not always know the analogue in Russian.
There is a function that initializes an array consisting of structures. The function works, but Valgrid throws the error "12 bytes are definitely lost ..."

void init_product(struct product *pr, const char *title, const char *code,
        int stock, double price)


{   char *temp;
    temp = title;
    temp = malloc(strlen(title) + 1);
    if (temp == NULL){
       return NULL;
    }
        
    strcpy(temp, title);
        title = temp;
        pr->title = title;  
        
        
        int i = 0;
        while (*code) {
            pr->code[i] = (*code);
            code++;
            i++;
            if (i == 7)
                break;
        }
        pr->code[i] = '\0';
          
        
pr->stock = stock;
pr->price = price;

}

The memory for the title field was dynamically allocated, so now it must be freed by changing main.c to do this
int main()
{
    struct product p;
    init_product(&p, "test", "1234", 1, 0.50);
}

And here I don't know what to do.
free(p.title)Does not help. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2015-04-08
@jcmvbkbc

There is a function that initializes an array consisting of structures.

In your example, a single instance of the struct is initialized.
Show the definition of this structure.
It's not clear without a definition, but it seems you are writing to an uninitialized array.
And it should. Is the error from Valgrind the same? Add --track-origins=yes for clarity.

V
Vladimir Martyanov, 2015-04-08
@vilgeforce

I suspect the problem is here:
title = temp;
pr->title = title;
Do pr->title = temp; and check.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question