2016-11-05 21 views
-2

我正在處理這段代碼來分配一些內存和返回指針,但我得到了段錯誤的錯誤。請幫我弄明白。我正在處理這段代碼來分配一些內存和返回指針,但我得到了段錯誤的錯誤

#include <stdio.h> 
#include <stdlib.h> 
#include "memalloc.h" 
int total_holes,sizeofmemory; 
void* start_of_memory; 
void setup(int malloc_type, int mem_size, void* start_of_memory) { 
/** 
* Fill your code here 
* 
**/ 
    sizeofmemory=mem_size; 
    //initionlize memory 
    start_of_memory = (int *) malloc(mem_size*sizeof(int)); 
    if(malloc_type==0) 
    { 
     //first of 
     printf("first fit"); 
     void firstfit(); 
    } 
    else if(malloc_type==1) 
    { 
     //first of 
     printf("best fit"); 
     void bestfit(); 
    } 
    else if(malloc_type==2) 
    { 
     //first of 
     printf("worst fit of"); 
     void worstfit(); 
    } 
    else if(malloc_type==3) 
    { 
     //first of 
     printf("Buddy system"); 
     void buddyfit(); 
    } 


} 

void *my_malloc(int size) { 
/** 
* Fill your code here 
* 
**/ 

    //chek pointer in null or not 
    if((start_of_memory = malloc(size)) == NULL) { 
     printf("no memory reserve"); 
     } 
     else{ 
      //add more memory in void pointer 

      start_of_memory=start_of_memory+size; 
     }   
    return (void*)-1; 
} 

void my_free(void *ptr) { 
/** 
* Fill your code here 
* 
**/ 
    free(ptr); 
} 

int num_free_bytes() { 
/** 
* Fill your code here 
* 
**/ 
    //count number of free bytes i 
    int sum=0; 
    for(int i=0;i<sizeofmemory;i++) 
    { 
     if(start_of_memory+i==0) 
     { 
      sum++; 
     } 
    } 
    return sum; 
} 

int num_holes() { 
/** 
* Fill your code here 
* 
**/ 
    // call function num_free_bytes and check free space 
    total_holes=num_free_bytes(); 
    return total_holes; 
} 
//memalloc.h 

void setup(int malloc_type, int mem_size, void* start_of_memory); 
void *my_malloc(int size); 
void my_free(void* ptr); 
int num_free_bytes(); 
int num_holes(); 
#define FIRST_FIT  0 
#define BEST_FIT  1 
#define WORST_FIT  2 
#define BUDDY_SYSTEM 3 
+1

'my_malloc'總是返回-1 –

+0

您是否嘗試過通過調試器來運行呢? –

回答

0

下面的代碼可能更接近你想要的。通常,自定義malloc函數返回指向分配內存開始的指針,而不是指向結尾的內存。您的原始函數永遠不會返回任何分配的內存,但 (void *)(-1)

void *my_malloc(int size) { 
void * start_of_memory; 
//check pointer if null or not 
if((start_of_memory = (void *)malloc(size)) == NULL) { 
    printf("no memory reserve"); 
     return NULL; // no memory 
    } 
    else{  
     return (start_of_memory); 
    } 

}

+0

+ sg7但運行一些模擬程序後,程序仍然崩潰...如果你可以幫助...這將是偉大的... –

+0

@YasirMehmood - 張貼您的'主',我可以看看。 – sg7

+0

'malloc()'已經返回一個void指針嗎?我看到有人將它轉換爲int *'或'char *'或'struct name *',但他們不鼓勵這樣做。當'malloc'未能保留內存時,它返回NULL,隨後將其分配給'start_of_memory'。你真的需要有2個不同的return語句,儘管'start_of_memory'將包含一個NULL或一個內存位置? – alvits

相關問題