[英]Allocate, free, allocate variable
I am using the GSL library to write some C code. 我正在使用GSL库编写一些C代码。 I'm noticing some sort of inconsistency (at least from my limited knowledge of C) in allocating, freeing, and allocating a variable in my code using the GSL library. 我注意到使用GSL库在代码中分配,释放和分配变量时存在某种不一致(至少从我对C的有限了解)。 When the first allocation is inside the loop, things work just fine, eg 当第一个分配在循环内时,一切正常,例如
int i;
for(i=1; i < 101; i++){
gsl_matrix * W = gsl_matrix_alloc(10,10);
gsl_matrix_free(W);
}
In another function, I have the initial allocation before the loop, 在另一个函数中,我在循环之前有初始分配,
int i;
gsl_matrix * W = gsl_matrix_alloc(10,10);
for(i=1; i < 101; i++){
gsl_matrix_free(W);
gsl_matrix * W = gsl_matrix_alloc(10,10);
}
and it DOES NOT work. 它不起作用。 Lastly, if I take out the gsl_matrix *
in the loop, it works. 最后,如果我在循环中取出gsl_matrix *
,它将起作用。 Eg 例如
int i;
gsl_matrix * W = gsl_matrix_alloc(10,10);
for(i=1; i < 101; i++){
gsl_matrix_free(W);
W = gsl_matrix_alloc(10,10);
}
Does anyone have an explanation? 有人有解释吗? Why does the placement of the first allocation inside or outside of the loop matter? 为什么第一个分配在循环内还是循环外的位置很重要?
Your compiler should give you a warning with a hint to the explanation - something to the effect that variable W
re-declared inside the loop hides variable W
declared outside the loop. 你的编译器应该给你的提示,说明一个警告-这是该变量的影响W
内循环再声明,隐藏变量W
外循环声明。
The reason the second loop does not work is that you are re-declaring W
, instead of re-assigning it. 第二个循环不起作用的原因是您要重新声明W
,而不是重新分配它。 That is why only the first iteration frees matrix W
correctly; 这就是为什么只有第一次迭代才能正确释放矩阵W
; subsequent iterations free a dangling pointer, causing undefined behavior. 随后的迭代释放了一个悬空的指针,从而导致未定义的行为。
Removing gsl_matrix *
from the second line makes this a re-assignment, as intended, so the code works again. 从第二行删除gsl_matrix *
可以按预期进行重新分配,因此代码可以再次使用。
Note that W
points to the last allocated matrix, which needs to be freed in order to avoid memory leaks: 请注意, W
指向最后分配的矩阵,需要释放该矩阵以避免内存泄漏:
gsl_matrix * W = gsl_matrix_alloc(10,10);
for(i=1; i < 101; i++){
gsl_matrix_free(W);
W = gsl_matrix_alloc(10,10); // re-assign
}
gsl_matrix_free(W); // Avoid memory leaks
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.