Search code examples
cpointersstructmallocfree

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.


Solution

  • 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