無法使用sizeof的技巧來取得陣列長度
不過可以寫一個自己的malloc和free來計算並維護各個動態分配的長度!!
- 寫mymalloc在malloc時記錄下這塊記憶體的陣列元素個數
- 寫myfree在free時把記錄下來的對應刪掉
#include
#include
#include
typedef struct arr_sz_t{
void * pointer;
int length;
struct arr_sz_t *next;
}arr_sz;
static arr_sz *sz_mapping;
void* mymalloc(int length, int size);
void myfree(void *p);
void add_sz_entry(void* p, int length);
int arr_length(void* p);
//input 1.array length 2.unit size
void* mymalloc(int length, int size){
void* ret = malloc(length*size);
add_sz_entry(ret, length);
return ret;
}
//free with mapping table
void myfree(void *p){
free(p);
if(sz_mapping != NULL){
arr_sz * t;
t = sz_mapping;
if(t->pointer == p){
sz_mapping = t->next;
free(t);
return;
}
while(t->next != NULL){
arr_sz *next;
next = t->next;
if(next->pointer == p){
t->next = next->next;
free(next);
return;
}
t = t->next;
}
}
}
void add_sz_entry(void* p, int length){
arr_sz* t = (arr_sz *)malloc(sizeof(arr_sz));
t->next = NULL;
t->pointer = p;
t->length = length;
//no sz_mapping
if(sz_mapping == NULL){
sz_mapping = t;
}
//insert
else{
t->next = sz_mapping;
sz_mapping = t;
}
}
//if no mach in mapping table, size is 0
int arr_length(void* p){
//no mapping data
if(sz_mapping == NULL){
return 0;
}
arr_sz* t;
t = sz_mapping;
while(t != NULL){
if(t->pointer == p){
return t->length;
}
t = t->next;
}
return 0;
}
int main(void){
srand(time(0));
int *data[50];
int i;
for(i=0;i<50;i++){
data[i] = (int *)mymalloc(random()%50, sizeof(int));
printf("size of data[%d]: %d\n", i, arr_length(data[i]));
myfree(data[i]);
}
return 0;
}
沒有留言:
張貼留言