Персональная функция malloc, которая использует структуру данных для обработки памяти - PullRequest
0 голосов
/ 14 марта 2011

У меня есть эта функция, которая будет занимать несколько байтов для выделения и отправки обратно, только если она доступна и размер запрошенного количества байтов помещается в мою небольшую управляемую память.Мой вопрос:

Соответствующая структура данных не выделяется, и, боюсь, я не верну правильные адреса.Кто-нибудь знает, как я могу проверить эту функцию, используя ее в качестве библиотеки в другой программе?

СТРУКТУРА ДАННЫХ

typedef struct memBlock{
struct memBlock* next;
unsigned long size;  // Size of this block
unsigned int is_used;  // bool 0 = not used 1 = used
} memBlock;

ФУНКЦИЯ МАЛЛОКА:

char *mm_alloc(unsigned long no_of_chars){

if (!has_initialized) {
    printf("No Memory has been intialized, PLEASE INITIALIZE THE MEMORY BEFORE calling This function\n");
    exit(1);
}


void *cur_location; // this is where we are currentl in our memory pool

memBlock *current_loc_mb; // the current mem block location

char *mem_location; // mem location we will return to the user

/* We are going to have to include the size of our data struct when we are searching for open memory*/
no_of_chars = no_of_chars + sizeof(struct memBlock);

mem_location = 0; // set to 0 until a proper size has been found

cur_location = managed_memory_start; // start at the beginning of our allocated memory

// go until there is no more memory left, allocate until we get to the end of our managed memory
while (managed_memory_start != NULL) {

    /*cur_location and cur_loc_mcb are at the same address initially,
but we use the current location as a pointer to move around our managed memory*/

    cur_loc_mcb = (memBlock *)cur_location; 

    // if our current location is not used
        if (!cur_loc_mcb->is_used) {

            if (cur_loc_mcb->size >= no_of_chars) {

                // we have found a size big enough or equal to what the user asks for
                cur_loc_mcb->is_used = 1; 
                mem_location = cur_location; 

                break;

            }
        }

// at this point we dont have a size big enough, move to the next one
cur_location = cur_location + cur_loc_mcb->size; 

}
/*Move the memory past or MCB and return*/

mem_location = mem_location + sizeof(struct memBlock);

return mem_location;
}

1 Ответ

0 голосов
/ 14 марта 2011

Где-то в вашем коде вы устанавливаете mem_location

            mem_location = cur_location;

и позже, непосредственно перед возвратом его значения, вы меняете его

    mem_location = mem_location + sizeof(struct memBlock);

это не кажется правильным ...

...