[英]Malloc and free in loop in C
Is it always necessary to match malloc() and free() calls? 是否总是需要匹配malloc()和free()调用? 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?
我可以覆盖动态内存中的数据,还是应该先释放它们然后再次分配malloc? 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. 另一种方法是在循环之前执行malloc,并在循环内部执行free()。 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};
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: 在您的情况下,如果您在
while
循环的每次迭代中使用test
结构,我将编写如下代码:
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);
调用
free(test_p);
, you shouldn't use test_p
again. ,您不应再使用
test_p
。 It means the test_p
only be valid in the first time of loop. 这意味着
test_p
仅在第一次循环中有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.