Q:

What's wrong with my C code(My output is volatile because of malloc)?

I SOMETIMES get errors when executing this code:
#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;
}

And this is the output:
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)

First number is to count how much input the user wants, (in this case 3) and the 2nd(in this case, 2nd, 3rd and 4th) number is the number you want to test whether its a Fibonacci number or not.
Sorry if this is very hard-to-read code, I have a lot to learn. 

A:

You are not allocating enough memory, thus you corrupt the heap. sizeof() applied on a pointer (as in your program) usually results in 4 or 8, depending on the architecture. Obviously, this might just be enough for test, but is definitely too little for table.
You need to figure out how much memory you really need, and use this as argument in malloc.

