我正在研究这个代码来分配一些内存和返回指针,但我得到分段错误错误

时间:2016-11-05 17:50:01

标签: c linux segmentation-fault dynamic-memory-allocation

我正在研究这段代码来分配一些内存和返回指针,但我得到了分段错误错误。请帮我搞清楚。

#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 个答案:

答案 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); 
    }

}