简体   繁体   中英

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM