Bonjour je dois ecrire les fonction malloc calloc realloc et free pour qu'ils agissent exactement comme ceux de la bibliothe (stdlib).le maximun de memoire a allouer est 1MB et je dois gerer toutes les erreurs d'allocation.jai ecris une partie mais jai des pb avec la fonction malloc.Si quelqu'un l'a deja fais j'aimerai bien voir les codes pour comparer et me debloquer.Sinon j'aimerai bien de l'aide.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130 #include "halde.h" #include <unistd.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #define KENNUNG ((void*)0x00beef00) #define SIZEMBLOCK (sizeof(mblock)) #define MB (1024*1024) /* Speicherverwaltung */ typedef struct mblock { size_t size; struct mblock *next; } mblock; /* globale Variablen */ static char *newmem = NULL; static mblock *fsp = NULL; int bloecke = 0; static mblock *getMblock(void *ptr) { if(NULL == ptr) return NULL; return (mblock *)((char *)ptr - SIZEMBLOCK); } static void init() { newmem = (char *)sbrk(MB); if(-1 == (int)newmem) { perror("sbrk"); exit(EXIT_FAILURE); } else { fsp = (mblock *)newmem; fsp->size = MB-SIZEMBLOCK; fsp->next = NULL; } } void *malloc(size_t size) { mblock *fsp_alt = fsp; mblock *fsp_neu = fsp; mblock *fsp_merken = fsp; int units = 0; int lauf = 0; if(NULL == newmem) { init(); } if(size == 0) return (void *)1; while(fsp_alt && fsp_alt->size < size) { /* Speicher finden */ fsp_merken = fsp_alt; fsp_alt = fsp_alt->next; lauf++; } if(!fsp_alt) { errno = ENOMEM; return NULL; } units = ((size-1) / SIZEMBLOCK) + 1; if(fsp_alt->size > (((units + 1) * SIZEMBLOCK) + SIZEMBLOCK)) { fsp_neu = fsp_alt + 1 + units; fsp_neu->size = fsp_alt->size - (units + 1) * SIZEMBLOCK; fsp_neu->next = fsp_alt->next; } else { fsp_neu = fsp_alt->next; } fsp_alt->next = KENNUNG; bloecke++; if(fsp_alt == fsp) fsp = fsp_neu; else { fsp_merken->next = fsp_neu; } return ((void *)(fsp_alt + 1)); } void free(void* ptr) { mblock *tmp = NULL; if(NULL == ptr || ptr == (void *)1) return; tmp = getMblock(ptr); if(tmp->next != KENNUNG) { abort(); } else { tmp->next = fsp; fsp = tmp; } } void *realloc(void *ptr,size_t size) { mblock *tmp = getMblock(ptr); if(ptr == (void *)1 || ptr == NULL) { return malloc(size); } if(size == 0) { free(ptr); return NULL; } if(size == tmp->size) { return ptr; } else { void *new = NULL; free(ptr); new = malloc(size); if(new != ptr) new = memcpy(new,ptr,tmp->size); return new; } return NULL; } void *calloc(size_t nmemb, size_t size) { void *new = malloc(nmemb*size); if(new) memset(new,0,nmemb*size); return new; }
Partager