mehtame026
mehtame026

Reputation: 125

Malloc and free in loop in C

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.

Upvotes: 0

Views: 2857

Answers (3)

Nan Xiao
Nan Xiao

Reputation: 17467

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.

Upvotes: 0

Ryan Haining
Ryan Haining

Reputation: 36792

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

Upvotes: 1

Peter
Peter

Reputation: 508

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);

Upvotes: 0

Related Questions