I have a case where I am calling a function twice, using two different sets of variables. The first call results in a segmentation fault, the second call returns successfully.
The parameters are identical, short of the variable names. What could be the cause of this behavior?
#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);
}
The function prototype in a separate header file:
int *power_arr(int *n, int nlength, int exp, int *res_length);
I cant discern any difference between the first call to power_arr
and the second call. Any insight into what exactly is occurring here?
EDIT:
Source for function 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;
}
Note, I have placed to printf
statements for debugging. I have commented where the code execution fails.