我正在处理这段代码来分配一些内存和返回指针,但我得到了段错误的错误

问题描述:

我正在处理这段代码来分配一些内存和返回指针,但我得到了段错误的错误。请帮我弄明白。我正在处理这段代码来分配一些内存和返回指针,但我得到了段错误的错误

#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

您是否尝试过通过调试器来运行呢? –

下面的代码可能更接近你想要的。通常,自定义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