int spm_alloc(int bytes) { assert(spm_used_size + bytes <= spm_size); int blocks = bytes/spm_block_size + (bytes%spm_block_size?1:0); /* first try */ int loc = first_fit(blocks); if (loc == -1) { defrag(); spm_need_defragment = 1; } else { spm_need_defragment = 0; } /* set the bits of the used blocks */ loc = first_fit(blocks); assert(loc != -1); for (int k = 0; k < blocks; k++) { set(loc + k); } spm_used_size += blocks * spm_block_size; spm_internal_fragment += spm_block_size - bytes%spm_block_size; return loc; }
/*=============================================*/ char *tas_malloc (size_t taille) { int pred; int p; p=first_fit(taille,&pred); if (p == libre) { libre += p + taille-1; tas[libre] = tas[p] - taille-1; tas[libre+1] = tas[p+1]; tas[p] = taille; printf("#== p (libre) : %d ==#\n",p); } else if (tas[p]-taille < TAILMIN) { tas[p+taille+1] = tas[p] - taille-1; tas[p+taille+2]=tas[p+1]; tas[pred+1]+=taille+1; tas[p]=taille; printf("#== Else if : %d ==#\n",p); } else { tas[pred+1] = tas[p+1]; printf("#== Else : %d ==#\n",p); } return &tas[p+1]; }
/* void* change_entry(void* entry, int offset, int size) { } */ void* first_fit(kma_size_t size) { int min_size = sizeof(entry_t*); page_t* first_page = (page_t*)(gpage_entry->ptr); entry_t* entry = (entry_t*)(first_page->first); if(size < min_size) size = min_size; while(entry) { if(size > entry->size) { entry = entry->next; continue; } else if(size >= entry->size - min_size) { delete_entry(entry); return (void*)entry; } else { add_entry((void*)(entry + size), entry->size - size); delete_entry(entry); return (void*)entry; } } kma_page_t* new_page = get_page(); init_page(new_page); return first_fit(size); }
void *my_firstfit_malloc(int size) { void *rslt; // Check to see if the Linked List has been initialized or not if (head.next == NULL) { Node *node_ptr = (Node *) sbrk(sizeof(Node)); // Put descriptor Node on the heap void *allocation_ptr = (void *) sbrk(size); // Put the allocation on the heap node_ptr -> address = allocation_ptr; // Store the address of the allocation in to the descriptor node node_ptr -> offset = size; // Store the size of the allocation in the descriptor node node_ptr -> flag = 1; // Store the fact that it is not an empty allocation on to the descriptor node node_ptr -> next = &tail; node_ptr -> prev = &head; head.next = node_ptr; // Initialize linked list head.prev = NULL; tail.prev = node_ptr; tail.next = NULL; return (void *) node_ptr->address; } rslt = (void *) ((void *)first_fit(size)) + sizeof(Node); return rslt; }
/* Vérification du mode: -n : next_fit -f : first_fit -b : best_fit */ void verification_mode(char* mode) { int* tab_objets = (int*) malloc(sizeof(int) * n_objets); if (strcmp(mode, "-n") == 0) { printf("Mode NextFit : OK\n"); next_fit(tab_objets); return; } if (strcmp(mode, "-f") == 0) { printf("Mode FirstFit : OK\n"); first_fit(tab_objets); return; } if (strcmp(mode, "-b") == 0) { printf("Mode BestFit : OK\n"); best_fit(tab_objets); return; } free(tab_objets); perror("Le mode n'existe pas..."); exit(EXIT_FAILURE); }
/* * malloc */ void *malloc (size_t size) { //printf("\nMalloc Count: %d\n",++malloc_count); size_t asize; size_t extendsize; char *bp; /* Ignore spurious requests */ if (size <= 0) return NULL; /* Adjust block size to include overhead and alignment reqs */ asize = MAX(ALIGN(size) + DSIZE, HEADER_SIZE); /* Search the free list for a fit */ if ((bp = first_fit(asize))) { alloc(bp, asize); //mm_checkheap(1); return bp; } extendsize = MAX(asize, CHUNKSIZE); if ((bp = extend_heap(extendsize/WSIZE)) == NULL) return NULL; //return NULL if unable to get heap space alloc(bp, asize); //mm_checkheap(1); return bp; }
void solve_bin_packing(const std::vector<uint32_t> &items) { uint32_t total_weight = std::accumulate(items.begin(), items.end(), 0); uint32_t num_bins = first_fit(items, 100); printf("weight: %4u, num_bins: %3u, valid: %s\n", total_weight, num_bins, validate_solution(total_weight, num_bins)?"true":"false"); }
/** Allocate an extent of the specified size (first fit) from the extent map, removing the returned extent from the map. */ Extent ExtentMap::allocate_first_fit(rose_addr_t size) { iterator found = first_fit(size, begin()); if (found==end()) throw std::bad_alloc(); Extent retval(found->first.first(), size); erase(retval); return retval; }
/** * Malloc for garbage collection, uses first fit * @arg alloc_size size of allocated memory (in bytes) */ void * GC_malloc(size_t alloc_size) { header_t *block_ptr; block_ptr = first_fit(&freeptr, alloc_size); if(block_ptr == NULL) { block_ptr = morecore(alloc_size); } //Add to used blocks add_to_list(&usedptr, block_ptr); //Give word aligned memory return start_of_block(block_ptr); }
void *free_allocation(info_p handler, long n_bytes){ int full_mem=0; if(n_bytes < 0){ printf("Free Allocation Error: requested negative space\n"); return NULL; } if(handler->n_bytes < n_bytes){ printf("Free Allocation Error: requested too much space\n"); return NULL; //User requested more space than permitted } if(n_bytes == handler->n_bytes){ //printf("request:%lu; bytes: %lu; declaring full memory\n", n_bytes, handler->n_bytes); full_mem=1; } if(handler->free_list == NULL){ return NULL; } void *mem = handler->memptr-4; //printf("free list head: %p; size of mem is: %lu\n",handler->free_list, *(long *)mem); switch(handler->flags){ case (FREE1_ALLOC): //first fit return first_fit(handler, handler->free_list, n_bytes,full_mem); break; case (FREE2_ALLOC): //next fit return next_fit(handler, n_bytes); break; case (FREE3_ALLOC): //best fit return best_fit(handler, n_bytes); break; case (FREE4_ALLOC): //worst fit return worst_fit(handler, n_bytes); break; default: //should never happen return NULL; } printf("Not enough memory to allocate\n"); return NULL; }
void* kma_malloc(kma_size_t size) { int malloc_size = size + sizeof(void*); if(malloc_size > PAGESIZE) return NULL; if(!gpage_entry) { gpage_entry = get_page(); *((kma_page_t**)gpage_entry->ptr) = gpage_entry; init_page(gpage_entry); printf("init success\n"); gflag = 1; } void* _first_fit = first_fit(size); printf("first_fit success\n"); return _first_fit; }
/* * @brief Détermine la bonne méthode d'allocation * * @param kv descripteur d'accès à la base * @param key clé * @param val valeur * @param offset index dans le .kv modifié par effet de bord */ int kv_put_dkv(KV *kv, const kv_datum *key, const kv_datum *val, len_t *offset) { if(kv->alloc == 0) { return first_fit(kv, key, val, offset); } else if(kv->alloc == 1) { return worst_fit(kv, key, val, offset); } else if(kv->alloc == 2) { return best_fit(kv, key, val, offset); } else { errno = EINVAL; return -1; } }
void *next_fit(info_p handler, long n_bytes){ void *curr = handler->free_list; void *prev = NULL; printf("Last Allocation: %p\n", handler->last_alloc); if(handler->last_alloc == NULL){ return first_fit(handler, handler->free_list, n_bytes, 0); } while(curr < handler->last_alloc){ prev = curr; curr = *(long **)curr; } //Look for next available free space after previous allocated region while(curr != NULL){ if(free_size(curr) >= n_bytes){ //edit free list, insert size in first four bytes, and return pointers if(free_size(curr) == n_bytes) //exact fit (good) return allocate_to_list_exact(handler, handler->free_list, curr, n_bytes, prev); if((free_size(curr) - n_bytes) >= 8) //Leaves block large enough for 4 byte size + 4 byte data return allocate_to_list(handler, handler->free_list, curr, n_bytes, prev); //Otherwise, the chunk does not work! } prev = curr; //keep track of previous node curr = *(long **)curr; }//hit the end of list, go back to beginning prev = NULL; curr = handler->free_list; while(curr < handler->last_alloc){ if(free_size(curr) >= n_bytes){ //edit free list, insert size in first four bytes, and return pointers if(free_size(curr) == n_bytes) //exact fit (good) return allocate_to_list_exact(handler, handler->free_list, curr, n_bytes, prev); if((free_size(curr) - n_bytes) >= 8) //Leaves block large enough for 4 byte size + 4 byte data return allocate_to_list(handler, handler->free_list, curr, n_bytes, prev); //Otherwise, the chunk does not work! } prev = curr; //keep track of previous node curr = *(long **)curr; } return NULL; }
int main() { printf("请输入内存大小\n"); int n; scanf("%d", &n); NODE *phead; //空闲链 init_list(&phead, 0); init_list_a(phead, n); //init_list_b(phead, n); NODE *head; init_list(&head, 0); NODE *hd; init_list(&hd, 0); printf("首次适应算法-1 循环首次适应算法-2 最佳适应算法-3 最坏适应算法-4\n"); int ch; scanf("%d", &ch); while (1) { if (ch == 1) { first_fit(phead, head, hd); break; } else if (ch == 2) { next_fit(phead, head); break; } else if (ch == 3) { best_fit(phead, head); break; } else if (ch == 4) { best_fit1(phead, head); break; } } return 0; }
//only add function called from SRT or RR. Determines which memory algorithm to use bool Memory::add_memory(char proc, int proc_size, int time){ if(algo == "First-Fit"){ first_fit(proc, proc_size, time); } else if(algo == "Next-Fit"){ next_fit(proc, proc_size, time); } else if(algo == "Best-Fit"){ best_fit(proc, proc_size, time); } else{ return false; } printMem(time); return true; }
/* * mm_malloc - Allocate a block by incrementing the brk pointer. * Always allocate a block whose size is a multiple of the alignment. */ void *mm_malloc(size_t size) { int newsize = ALIGN(BLK_HDR_SIZE + size); //making the size aligned to 8. blockHdr *bp = first_fit(newsize); // traversing the heap to get the first freeblock using first fit if(bp==NULL) // required free space not available { bp = mem_sbrk(newsize); if ((long)bp == -1) // requested space is not available in the memory return NULL; else // requested space present in the memory bp->size = newsize | 1; // setting the status : allocated } else{ // implementing the functionality of 'extend_heap' bp->size |= 1; bp->prev->next = bp->next; bp->next->prev = bp->prev; } return (char *)bp + BLK_HDR_SIZE; // returning the payload }
int main(void) { /* ------------------------------------------------- */ /* PARTE 1: Declaração de variáveis locais da main */ /* ------------------------------------------------- */ int outputfd; /* Descritor de arquivos abertos = Retorno de open */ int retorno; /* Valor de retorno de dup */ int i = 0, j = 0, m = 1, l = 1, n = 1, q; /* Contadores auxiliares */ int numero_processo; /* Número do processo */ int tamanho_processo; /* Memória requerida pelo processo */ int qtd_info_processo; /* Total de entradas que descrevem a execução do processo */ int id; /* Identificador do algoritmo de alocação escolhido */ processo *proc_v; /* Vetor de processos */ int tempo; /* Tempo de execução ou de espera */ char s[5]; /* Nome da informação do processo (exec ou io) */ mem *M; /* Memória */ int qtd_processos = 0; /* Quantidade de processos */ int tempo_total = 0; /* Tempo total de todos os processos */ /* ------------------------------------------------- */ /* PARTE 1: Exibição da mensagem inicial */ /* ------------------------------------------------- */ cabecalho(); espera_enter(); /* ------------------------------------------------- */ /* PARTE 2: Abertura do arquivo de entrada */ /* ------------------------------------------------- */ /* Tratamento de erro para abertura do arquivo 'entrada.txt' */ if ((outputfd = open("files/entrada.txt", O_RDONLY, 0666)) == -1) { showError("Falha na abertura do arquivo 'entrada.txt'.\n", ERR_FOPEN); } /* ------------------------------------------------- */ /* PARTE 3: Redirecionamento da entrada padrão */ /* ------------------------------------------------- */ close(0); /* Fechamento da entrada stdin (teclado) */ /* Tratamento de erro para duplicação de stdin */ if ((retorno = dup(outputfd)) == -1) { /* Duplicação de stdin (menor descritor fechado) */ showError("Falha na duplicação de stdin.\n", ERR_DUP); } /* ------------------------------------------------- */ /* PARTE 4: Leitura do arquivo de entrada */ /* ------------------------------------------------- */ printf("-----------------------------------------------------------------------------------\n\n"); printf(ANSI_COLOR_MAGENTA "LEITURA DO ARQUIVO DE ENTRADA:" ANSI_COLOR_RESET "\n\n"); printf("-----------------------------------------------------------------------------------\n\n"); sleep(2); scanf("%d [^\n]", &qtd_processos); /* Lê a quantidade de processos */ printf("- Número total de processos: %d\n\n", qtd_processos); sleep(1); /* Aloca memória para um vetor de processos */ proc_v = (processo*) malloc(qtd_processos * sizeof (processo)); /* Aloca memória para uma estrutura de memória */ M = (mem*) malloc(sizeof (mem)); /* Inicializa o tempo dos processos */ for (q = 0; q < qtd_processos; q++) { proc_v[q].tempo_total = 0; } for (i = 0; i < qtd_processos; i++) { scanf("Processo #%d – %dMb [^\n]", &numero_processo, &tamanho_processo); /* Lê o número identificador do processo e o seu tamanho em Mb */ proc_v[i].numero = numero_processo; proc_v[i].tamanho = tamanho_processo; printf("-----------------------------------\n"); printf("PROCESSO #%d\n", proc_v[i].numero); printf("-----------------------------------\n"); sleep(2); printf("- Número do processo: %d\n", proc_v[i].numero); printf("- Tamanho do processo: %dMb\n", proc_v[i].tamanho); printf("-----------------------------------\n"); sleep(2); scanf("%d [^\n]", &qtd_info_processo); /* Lê a quantidade de informações do processo */ proc_v[i].qtd_info = qtd_info_processo; /* Aloca memória para um vetor de informações do processo */ proc_v[i].infos = (info*) malloc(sizeof (info) * qtd_info_processo); for (j = 0; j < proc_v[i].qtd_info; j++) { scanf("%s %d [^\n]", s, &tempo); /* Lê o nome da informação (exec ou io) e o tempo de execução ou de espera */ strcpy(proc_v[i].infos[j].nome, s); proc_v[i].infos[j].tempo = tempo; proc_v[i].tempo_total = proc_v[i].tempo_total + tempo; tempo_total = tempo_total + tempo; /* Tempo total de todos os processos juntos */ printf("- Nome da %da informação: %s\n", l, proc_v[i].infos[j].nome); if (strcmp(proc_v[i].infos[j].nome, "io") == 0) { printf("- Tempo de espera %d: %ds\n", n, proc_v[i].infos[j].tempo); printf("-----------------------------------\n"); sleep(2); n++; l++; } else { printf("- Tempo de execução %d: %ds\n", m, proc_v[i].infos[j].tempo); printf("-----------------------------------\n"); sleep(2); m++; l++; } } printf("\n"); l = 1; m = 1; n = 1; } scanf("%d [^\n]", &id); /* Lê a opção do algoritmo de alocação que deve ser executado */ /* ------------------------------------------------- */ /* PARTE 5: Inicialização da memória */ /* ------------------------------------------------- */ /* Aloca memória para uma estrutura de memória */ M = (mem*) malloc(sizeof (mem)); inicializar_memoria(M); /* ------------------------------------------------- */ /* PARTE 6: Execução do algoritmo de alocação */ /* ------------------------------------------------- */ printf("Tempo total do(s) processo(s) = %ds\n\n", tempo_total); switch (id) { /* First Fit */ case 1: printf("-----------------------------------------------------------------------------------\n\n"); printf(ANSI_COLOR_CYAN "F I R S T F I T" ANSI_COLOR_RESET "\n\n"); printf("-----------------------------------------------------------------------------------\n\n"); sleep(2); first_fit(proc_v, M, qtd_processos, tempo_total); /* Next Fit */ //case 2: //next_fit(); /* Worst Fit */ //case 3: //worst_fit(); /* Best Fit */ //case 4: //best_fit(); } return 0; /* Sucesso */ }