C++ 一个完整的链表只能使用一个malloc
我正在写一个程序,将使用链表分配内存 目标是减少对malloc函数的调用次数 为此,我设想了以下分配函数:head Slot*和free_slotsint是分配器的一部分C++ 一个完整的链表只能使用一个malloc,c++,list,malloc,singly-linked-list,allocator,C++,List,Malloc,Singly Linked List,Allocator,我正在写一个程序,将使用链表分配内存 目标是减少对malloc函数的调用次数 为此,我设想了以下分配函数:head Slot*和free_slotsint是分配器的一部分 inline T* allocate(size_t length) { if(free_slots == 0){ head = (Slot<T>*) malloc(length * sizeof(Slot<T>) * NBR_NEW_OBJECT); free_
inline T* allocate(size_t length)
{
if(free_slots == 0){
head = (Slot<T>*) malloc(length * sizeof(Slot<T>) * NBR_NEW_OBJECT);
free_slots = NBR_NEW_OBJECT;
}
T* result = &(head->data);
head = static_cast<Slot<T>* >(head->next);
return result;
}
但是,第二次我们进入分配方法时,第一次出现segfault时,一切正常。
你有什么想法吗?似乎最好的方法是在之前初始化所有的Slot->next字段 因此,正确的实施应该是:
inline T* allocate(size_t length)
{
if(free_slots == 0){
head = (Slot<T>*) malloc(length * sizeof(Slot<T>) * NBR_NEW_OBJECT);
free_slots = NBR_NEW_OBJECT;
for(int i = 0; i < NBR_NEW_OBJECT; i++)
head[i].next = reinterpret_cast<Slot<T>* >(&head[i+1]);
}
T* result = &(head->data);
head = reinterpret_cast<Slot<T>* >(head->next);
free_slots--;
return result;
}
头=静态头->下一步;下一步初始化在哪里?为什么不使用标准?顺便说一下,你可能有一个数组的链接列表…为什么在C++中使用Maloc?为什么不使用?我不确定@BasileStarynkevitch到底指的是什么,是放弃努力改用std容器,还是用std容器代替手动mallocing。我强烈建议使用向量而不是手动malloc。因为对于大多数使用,新操作符会给malloc增加无用的开销,所以在低级分配器中直接调用malloc并不是那么荒谬。
inline T* allocate(size_t length)
{
if(free_slots == 0){
head = (Slot<T>*) malloc(length * sizeof(Slot<T>) * NBR_NEW_OBJECT);
free_slots = NBR_NEW_OBJECT;
for(int i = 0; i < NBR_NEW_OBJECT; i++)
head[i].next = reinterpret_cast<Slot<T>* >(&head[i+1]);
}
T* result = &(head->data);
head = reinterpret_cast<Slot<T>* >(head->next);
free_slots--;
return result;
}