2014-10-31 24 views
-2

我是c編程的初學者。我可以編寫自己的malloc函數,並將主要的方法代碼放入其中。它給出了以下錯誤。爲什麼C給出這個錯誤「大小」未申報(首次在此功能使用)?

test.c: In function ‘main’: 

test.c:38:30: error: ‘size’ undeclared (first use in this function) 

test.c:38:30: note: each undeclared identifier is reported only once for each function it appears in 

代碼

/*An horrible dummy malloc*/ 
    #include <stdio.h> 
    #include <sys/types.h> 
    #include <unistd.h> 

    void *malloc(size_t size); 



    void *malloc(size_t size){ 
    void *p; 
    p = sbrk(0); 
    //if sbrk dails , we return null 
    if(sbrk(size)==(void*)-1){ 
     return NULL; 
    } 
    printf("wada\n"); 
    return p; 
} 

typedef struct s_block *t_block; 

struct s_block{ 
    size_t size; 
    t_block next; 
    int  free; 
}; 


int main(){ 
    malloc(50); 
    malloc(100); 

    t_block b; 
    b = sbrk(0); 
    sbrk(sizeof(struct s_block)+size);//Error line (code 1) 
    b->size = size; //Error Line 
    return 0; 
} 

回答

1

在這一行:sbrk(sizeof(struct s_block)+size)你使用,你有沒有在任何地方定義的變量size。這在錯誤消息中明確說明。

順便說一句,你應該叫你的功能,而不是malloc

+1

我把大小= 20;在這個代碼之上,但也是相同的...............? – Natasha 2014-10-31 03:24:37

+2

也許int大小= 20;效果更好 – Martin 2014-10-31 03:26:06

相關問題