我真的不知道哪个标题更适合描述我的问题。我通过VirtualBox使用Linux。我正在使用 gcc 编译器。到目前为止,我一直在编写代码(300 行),没有类似的问题。突然,如果我输入一个新变量并设置一个值,我的代码中的其他变量会更改它们的值。我想知道我是否必须清理记忆或其他东西。
do
{
rand_arr = rpermute(dim_x * dim_y);
flag = 0;
for (t = 0; t < (dim_x * dim_y); t++)
{
x = rand_arr[t] / dim_x;
y = rand_arr[t] % dim_x;
if (arr[x][y] == 255)
{
current_distance = sqrt(pow(exit[0][0] - x, 2) + pow(exit[0][1] - y, 2));
if (x != 0 && arr[x - 1][y] != 254)
{
distance_up = sqrt(pow(exit[0][0] - (x - 1), 2) + pow(exit[0][1] - y, 2));
}
else
{
distance_up = max_distance + 10000000;
}
// Here there is a code computing similar math operations as
// current_distance and distance_up
min_dist[0] = distance_up;
min_dist[1] = distance_back;
// Here i continue setting in the min_dist array all the variables
// Here there is a bubblesort code to arrange the min_dist array
k = 0;
do
{
if (distance_up == min_dist[k] && arr[x - 1][y] == 0 && distance_up < current_distance)
{
arr[x - 1][y] = 255;
arr[x][y] = 0;
flag = 1;
break;
}
else if (distance_back == min_dist[k] && arr[x][y - 1] == 0 && distance_back < current_distance)
{
arr[x][y - 1] = 255;
arr[x][y] = 0;
flag = 1;
break;
}
// Here there is a code with if statements similar to the two above
k++;
} while (k < 4 && min_dist[k] < current_distance);
}
}
...
} while (...)
所以这个循环之前的每个变量都保持不变,但是如果我只设置一个新变量,例如int test=0;
,尽管新变量是独立的,但每个变量在这个循环中都会发生变化。我也在函数中使用malloc
;我想知道这是否是问题所在,但直到现在我都没有任何问题。
#include <assert.h> /* <<-- Here */
do
{
rand_arr = rpermute(dim_x * dim_y);
flag = 0;
for (t = 0; t < (dim_x * dim_y); t++)
{
x = rand_arr[t] / dim_x;
y = rand_arr[t] % dim_x;
if (arr[x][y] == 255)
{
current_distance = sqrt(pow(exit[0][0] - x, 2) + pow(exit[0][1] - y, 2));
if (x != 0 && arr[x - 1][y] != 254)
{
distance_up = sqrt(pow(exit[0][0] - (x - 1), 2) + pow(exit[0][1] - y, 2));
}
else
{
distance_up = max_distance + 10000000;
}
// Here there is a code computing similar math operations as
// current_distance and distance_up
min_dist[0] = distance_up;
min_dist[1] = distance_back;
// Here i continue setting in the min_dist array all the variables
// Here there is a bubblesort code to arrange the min_dist array
k = 0;
do
{
if (distance_up == min_dist[k] && arr[x - 1][y] == 0 && distance_up < current_distance)
{
assert (x > 0); // <<-- Here
arr[x - 1][y] = 255;
arr[x][y] = 0;
flag = 1;
break;
}
else if (distance_back == min_dist[k] && arr[x][y - 1] == 0 && distance_back < current_distance)
{
assert (y > 0); // <<--- Here
arr[x][y - 1] = 255;
arr[x][y] = 0;
flag = 1;
break;
}
// Here there is a code with if statements similar to the two above
k++;
} while (k < 4 && min_dist[k] < current_distance);
}
}
...
} while (1); // <<-- Here