我正在處理這段代碼來分配一些內存和返回指針,但我得到了段錯誤的錯誤。請幫我弄明白。我正在處理這段代碼來分配一些內存和返回指針,但我得到了段錯誤的錯誤
#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
'my_malloc'總是返回-1 –
您是否嘗試過通過調試器來運行呢? –