我已经找不到这样的问题,但如果存在的话,请随时将我重定向到答案。
下面我尽力用尽可能少的代码来复制我遇到的错误。 我在保留错误的同时删除了尽可能多的变量,并对复制它所需的值进行了硬编码;根据我的测试,我只留下了必须是该错误发生的变量的变量。首先,我传递一个值 epsilon
,一个double
值(value)1.0/3.0
。然后,我将其传递给 a_function
这需要 epsilon
和一些数组。我对部分输入数组执行一些基本复制,然后 epsilon
值的变化非常小。下面是代码摘录,其中我删除了声明和 include
声明。
int main(int argc, int argv[])
{
/* It doesn't matter what these arrays are filled with,
but they must be of length 13 */
int array1[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int array2[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int array3[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int array4[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int a_value = 2;
double a_double= 1.0/3.0;
printf("a_double: %.10lf\n", a_double);
a_function(array1, array2, array3, array4, a_value, a_double);
return 0;
}
void a_function(int *array1, int *array2, int *array3, int *array4,
int a_value, double a_double)
{
int m = 1;
/* This occurs regardless of value assigned to m (provided the
for loop is appropriately changed to not go out of bounds) */
int temp_array1[m];
int temp_array2[m];
for(int i = 12; i < 13; i++)
{
temp_array1[i] = array1[i];
temp_array2[i] = array2[i];
}
printf("a_double: %.10lf\n", a_double);
}
运行此代码会给出输出
$ ./a.out
a_double: 0.3333333333
a_double: 0.3333332539
似乎在以下情况下不会发生该错误:
- 数组的长度发生变化。
for
的终止条件循环更改为最后一个元素以外的其他元素(例如i < 12
不会导致错误)。- 任何包含的参数都会被删除。
- 当值为
m
时是硬编码的:m
的值是多少并不重要是,但如果数组是根据它定义的,则会出现错误。 - 当我直接在
main
中运行此代码时(即没有函数)。 - 当我拥有第一个
printf
时的a_double
在函数入口处(即直接在int m = 1
之前)。
导致此错误的原因是什么?我的猜测是,这与 C 中的函数调用和临时变量有关,但我不知道。如果我可以提供任何说明,请告诉我。
最佳答案
此代码具有未定义的行为:
int m = 1;
int temp_array1[m];
for(int i = 12; i < 13; i++)
{
temp_array1[i] = array1[i];
}
循环执行一次,i
为12。但数组长度为1,所以写入越界。
关于C:函数参数输入看似随机变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52472254/