簡體   English   中英

我的C代碼有什么問題(由於malloc,我的輸出不穩定)?

[英]What's wrong with my C code(My output is volatile because of 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)是您要測試其斐波那契數字的數字。 抱歉,如果這是很難閱讀的代碼,我有很多東西要學習。

您沒有分配足夠的內存,因此破壞了堆。 根據架構的不同,應用於指針(如程序中)的sizeof()通常結果為4或8。 顯然,這對於test可能就足夠了,但對於table來說絕對太少了。

您需要確定您真正需要多少內存,並將其用作malloc參數。

test = malloc(sizeof(test));
table = malloc(sizeof(table));

“ test”是char *類型的變量。 這樣的變量通常具有4或8個字節的大小。 因此,您為4或8個字節分配了內存,足夠用於4或8個字符。

“表”是int *類型的變量。 同樣,通常為4或8個字節。 分配4或8個字節通常足以容納1或2個int。 如果您嘗試存儲更多內容,那么事情將會嚴重出錯。

找出要分配的字符數和整數,然后調用例如table = malloc(required_elements * sizeof(int))。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM