C 中的 Malloc 和 free in loop
Malloc and free in loop in C
是否总是需要匹配 malloc() 和 free() 调用?我必须为结构分配动态内存,然后在一些操作后释放它。我可以覆盖动态内存中的数据还是应该先释放它们然后再 malloc?例如:
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);
另一种方法是在循环之前执行 malloc 并在循环内执行 free()。释放后我可以使用这个结构指针吗?例如:
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);
在此先感谢您的帮助和建议。
假设这是使用 flex-array 方法并且您的分配有意义,您可以在每次迭代期间重用您的内存。这将为您节省大量分配和释放时间。
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);
如果您想在每次迭代时 "clear" 您的结构,您可以在循环开始时使用复合文字。
do {
*test_p = (struct test){0};
当您不再需要某个对象时,释放它始终是一个好习惯。在您的情况下,如果您在 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);
在您的代码中:
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);
调用free(test_p);
后,您不应该再调用test_p
。这意味着test_p
只在第次循环中有效。
是否总是需要匹配 malloc() 和 free() 调用?我必须为结构分配动态内存,然后在一些操作后释放它。我可以覆盖动态内存中的数据还是应该先释放它们然后再 malloc?例如:
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);
另一种方法是在循环之前执行 malloc 并在循环内执行 free()。释放后我可以使用这个结构指针吗?例如:
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);
在此先感谢您的帮助和建议。
假设这是使用 flex-array 方法并且您的分配有意义,您可以在每次迭代期间重用您的内存。这将为您节省大量分配和释放时间。
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);
如果您想在每次迭代时 "clear" 您的结构,您可以在循环开始时使用复合文字。
do {
*test_p = (struct test){0};
当您不再需要某个对象时,释放它始终是一个好习惯。在您的情况下,如果您在 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);
在您的代码中:
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);
调用free(test_p);
后,您不应该再调用test_p
。这意味着test_p
只在第次循环中有效。