0
votes

Is it always necessary to match malloc() and free() calls? I have to allocate dynamic memory for structure and then free it after some operations. Can I overwrite the data in dynamic memory or I should free them first and malloc again? For examples:

int x =5,len = 100;

do{
    struct test *test_p = (struct test *) malloc(sizeof(struct test) + len);

 /* ---do some operation ----------  */

    free(test_p);
    x--;
}while(x);

Another approach is to do malloc before loop and do free() inside loop. Can i use this struct pointer after freeing it ? For Example:

int x =5, len = 100;
struct test *test_p = (struct test *) malloc(sizeof(struct test) + len);

do{

 /* ---do some operation ----------  */

    free(test_p);
    x--;
}while(x);

Thanks in advance for your help and suggestions.

3
Yes, you are supposed to release all allocated memory when you don't need it anymore. When you don't need it anymore. You don't have to allocate and release the same buffer every iteration of your loop, you can simply allocate it before the loop and release it after. - Havenard
No, you can't use memory after freeing it. You also can't free it more than once. - user253751

3 Answers

1
votes

Assuming this is using a flex-array approach and your allocation makes sense, you could reuse your memory during each iteration. This will save you a lot of time on allocating and freeing.

int x =5,len = 100;

struct test* test_p = malloc(sizeof *test_p + len);
do {
    // do some operation using test_p
    x--;
} while(x);
free(test_p);

If you want to "clear" your structure at each iteration, you can do so with a compound literal at the start of your loop.

do {
    *test_p = (struct test){0};

and there are better ways to malloc

0
votes

It is always a good practice to free an object when you no longer need it. In your situation, if you are using the test struct in each iteration of the while loop, I would write the code as follows:

int x =5,len = 100;
struct test *test_p = (struct test *) malloc(sizeof(struct test) + len);
do{
    /* ---do some operation ----------  */

    x--;
}while(x);
free(test_p);
0
votes

In your code:

int x =5, len = 100;
struct test *test_p = (struct test *) malloc(sizeof(struct test) + len);

do{

 /* ---do some operation ----------  */

    free(test_p);
    x--;
}while(x);

After calling free(test_p);, you shouldn't use test_p again. It means the test_p only be valid in the first time of loop.