我在main()中动态分配一个数组来存储通过我自己编码的PrimeFactors()函数计算出的任何数的素因子。 问题是,当数组的大小> = 4时,程序显示看起来像未定义的行为;读垃圾价值和诸如此类的东西。尺寸< 4。
我认为数组地址可能正在通过函数进行更改,因此main()会读取垃圾值,而不知道数组的“新”地址;似乎就是这种情况。
操作系统是Linux Ubuntu 18.04 LTS。
当我在学习时,我不想简单地使用向量而忘记这个问题。
为什么会发生这种情况,我该怎么做才能解决这个问题?我很无能为力,似乎google和SO也是如此。
这是main()代码:
int main(int argc, char* argv[])
{
unsigned long long n = atoll(argv[1]);
unsigned long long* factors = malloc(sizeof(unsigned long long));
if(factors == NULL)
{
printf("malloc failed to allocate factors\n");
return -1;
}
else
printf("First address in main() %p\n\n", (void *)&(factors[0]));
unsigned short int* size = malloc(sizeof(unsigned short int));
if(size == NULL)
{
printf("malloc failed to allocate size\n");
return -1;
}
PrimeFactors(factors, size, n);
printf("Last address in main() : %p\n", (void *)&(factors[0]));
for(int i = 0; i < *size; ++i)
printf("%llu\n", factors[i]);
free(factors);
free(size);
return 0;
}
这是PrimeFactors()代码:
int PrimeFactors (unsigned long long* factors, unsigned short int* size, unsigned long long n)
{
printf("In PrimeFactors() :\n");
*size = 2;
factors = realloc(factors, (*size) * sizeof(unsigned long long));
if (factors == NULL)
{
printf("realloc failed re-allocating factors array\n");
return -1;
}
else
printf("realloc() %d address in PrimeFactors() : %p\n", *size, (void *)&(factors[0]));
if (IsPrime(n))
{
factors[0] = n;
return 0;
}
unsigned short int factorsCount = 0;
for (unsigned long long i = 2; i <= n; ++i)
{
while(n % i == 0)
{
if(factorsCount >= *size)
{
factors = realloc(factors, ++(*size) * sizeof(unsigned long long));
if (factors == NULL)
{
printf("realloc failed re-allocating factors array\n");
return -1;
}
else
printf("realloc() %d address : %p\n", *size, (void *)&(factors[0]));
}
factors[factorsCount] = i;
++factorsCount;
n /= i;
}
}
printf("last address in PrimeFactors() : %p\n", (void *)&(factors[0]));
for(int i = 0; i < *size; ++i)
printf("%llu\n", factors[i]);
printf("Exiting PrimeFactors()...\n\n");
return 0;
}
编译标志:
gcc -Wall -Wshadow -Wpointer-arith main.c libMath.c -o learnlab.exe
执行命令:
./ learnlab 80
预期产出:
main()中的第一个地址0x5626aa180260
在PrimeFactors()中:
PrimeFactors()中的realloc()2地址:0x5626aa180260
realloc()3地址:0x5626aa180260
realloc()4地址:0x5626aa180260
realloc()5地址:0x5626aa180260
PrimeFactors()中的最后一个地址:0x5626aa180260
2
2
2
2
5
退出PrimeFactors()......
main()中的最后一个地址:0x5626aa180260
2
2
2
2
5
实际输出:
main()中的第一个地址0x5626aa180260
在PrimeFactors()中:
PrimeFactors()中的realloc()2地址:0x5626aa180260
realloc()3地址:0x5626aa180260
realloc()4地址:0x5626aa1812b0
realloc()5地址:0x5626aa1812b0
PrimeFactors()中的最后一个地址:0x5626aa1812b0
2
2
2
2
5
退出PrimeFactors()......
main()中的最后一个地址:0x5626aa180260
0
2
2
4113
7233098161058900294
对不起,这是一篇很长的帖子,我真的想办法让它缩短。谢谢。