I执行以下代码时有时会出错:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int digits(int n){
int count = 0;
while(n!=0)
{
n/=10; /* n=n/10 */
++count;
}
return count;
}
int fib(int n){
int r;
if(n == 1 || n == 0)
return 0;
else if(n == 2)
return 1;
r = fib(n-1) + fib(n-2);
return r;
}
void function(void){
char* test; //number you want to scan
int* table;
int length, length2, test2 = 0, number, l, random = 0, j = 1, buffer;
test = malloc(sizeof(test));
table = malloc(sizeof(table));
scanf("%s", test);
number = atoi(test);
length = strlen(test); //length of input test number
while(test2 < length + 1){
printf("fib(%d) = %dn", j, fib(j));
buffer = table[j - 1] = fib(j);
test2 = digits(buffer);
j++;
}
//input size of "table" into "length2"
length2 = j - 1;
for(l = 0; l < length2; l++){
if(table[l] == number){
printf("YESn");
random = 1;
break;
}
}
if(random == 0)
printf("NOn");
free(table);
free(test);
}
int main(void){
int num, i;
scanf("%d", &num);
for(i=0; i < num; i++){
function();
}
return 0;
}
这就是输出:
3
2
fib(1) = 0
fib(2) = 1
fib(3) = 1
fib(4) = 2
fib(5) = 3
fib(6) = 5
fib(7) = 8
fib(8) = 13
YES
*** Error in `./Am_I_a_Fibonacci_Number': free(): invalid next size (fast): 0x08384018 ***
Aborted (core dumped)
第一个数字是计算用户想要的输入量(在本例中为3),第二个数字(在本案中为2、3和4)是您想要测试其是否为斐波那契数的数字。很抱歉,如果这是很难阅读的代码,我有很多要学习。
您没有分配足够的内存,因此损坏了堆。应用于指针(如程序中)的sizeof()
通常会产生4或8,具体取决于体系结构。显然,这对test
来说可能刚刚足够,但对table
来说肯定太少了。
您需要计算出实际需要多少内存,并将其用作malloc
中的参数。
test = malloc(sizeof(test));
table = malloc(sizeof(table));
"test"是char*类型的变量。这样的变量通常具有4或8个字节的大小。因此,您可以为4或8个字节分配内存,这对于4个或8个字符来说已经足够了。
"table"是类型为int*的变量。同样,通常为4或8个字节。分配4或8个字节通常足够1或2个int。如果你试图储存更多的东西,事情就会出大问题。
弄清楚要分配多少个字符和int,然后调用例如table=malloc(required_elements*sizeof(int))。