<分区>
我有一个案例,我使用两组不同的变量调用了一个函数两次。第一次调用导致段错误,第二次调用成功返回。
除了变量名之外,参数完全相同。这种行为的原因可能是什么?
#include <stdio.h>
#include <stdlib.h>
#include "euler-v2.h"
#define POWER 1000
int main(void)
{
int i;
int base[] = { 2 };
int *r;
int *rlength;
// The below line causes a segmentation fault
r = power_arr(base, sizeof(base) / sizeof(int), 2, rlength);
int n[] = { 2 };
int *pow;
int *length;
pow = power_arr(n, sizeof(n) / sizeof(int), 2, length);
exit(0);
}
单独头文件中的函数原型(prototype):
int *power_arr(int *n, int nlength, int exp, int *res_length);
我看不出第一次调用 power_arr
和第二次调用有什么区别。是否了解这里到底发生了什么?
编辑:
函数 power_arr
的源代码:
int *power_arr(int *n, int nlength, int exp, int *res_length)
{
int i, j, tmp_length;
int *res, *tmp;
res = n;
printf("Step 1\n"); // Last printed line
*res_length = nlength;
printf("Step 2\n"); // Never reaches here
while (--exp > 0)
{
tmp_length = *res_length;
tmp = malloc(sizeof(int) * tmp_length);
if (!tmp)
{
return NULL;
}
copy(tmp, res, *res_length);
for (i = *n - 1; i > 0; i--)
{
res = sum(res, *res_length, tmp, tmp_length, res_length);
}
if (!res)
{
return NULL;
}
free(tmp);
}
return res;
}
请注意,我已将 printf
语句用于调试。我已经评论了代码执行失败的地方。