[英]Why does this malloc not work in C?
Just trying to make a kind of hash table with each node being a linked list. 只是尝试制作一种哈希表,每个节点都是一个链表。
Having trouble just initializing the space, what am I doing wrong? 初始化空间时遇到麻烦,我在做什么错?
#include <stdlib.h>
typedef struct entry {
struct entry *next;
void *theData;
} Entry;
typedef struct HashTable {
Entry **table;
int size;
} HashTable;
int main(){
HashTable *ml;
ml = initialize();
return 0;
}
HashTable *initialize(void)
{
HashTable *p;
Entry **b;
int i;
if ((p = (HashTable *)malloc(sizeof(HashTable *))) == NULL)
return NULL;
p->size = 101;
if ((b = (Entry **)malloc(p->size * sizeof(Entry **))) == NULL)
return NULL;
p->table = b;
for(i = 0; i < p->size; i++) {
Entry * b = p->table[i];
b->theData = NULL;
b->next = NULL;
}
return p;
}
You need to change sizeof(HashTable*)
to sizeof(HashTable)
and similarly sizeof(Entry **)
to sizeof(Entry *)
. 您需要将sizeof(HashTable*)
更改为sizeof(HashTable)
,类似地将sizeof(Entry **)
更改为sizeof(Entry *)
。 And the second thing is for every Entry
you need to allocate memory using malloc
again inside the loop. 第二件事是对于每个Entry
您需要在循环内再次使用malloc
分配内存。
if ((p = malloc(sizeof(HashTable))) == NULL)
return NULL;
p->size = 101;
if ((b = malloc(p->size * sizeof(Entry *))) == NULL)
return NULL;
I believe removing the malloc()
result casts is best practice. 我相信删除malloc()
结果转换是最佳实践。
Plus, as @Naveen was first to point out you also need to allocate memory for each Entry
. 另外,正如@Naveen首先指出的那样,您还需要为每个Entry
分配内存。
Firstly your sizeofs are wrong. 首先,您的sizeofs错误。 T * = malloc( num * sizeof(T)) is correct. T * = malloc(num * sizeof(T))是正确的。 You can also use calloc. 您也可以使用calloc。
You are reusing b for different purposes so it is quite confusing. 您正在出于不同的目的重用b,所以这很令人困惑。 Not generally good using a single character variable. 使用单个字符变量通常不好。
p->table which was b is allocated but not initialised, ie it doesn't point to anything useful, then you are trying to dereference it. p->原来是b的表已分配但未初始化,即它没有指向任何有用的东西,因此您尝试取消引用它。
You need to fill it will Entry* pointers first, and they must be pointing to valid Entry structs if you are going to dereference those. 您需要先将其填充Entry *指针,如果要取消引用它们,它们必须指向有效的Entry结构。
Your process probably dies on the line b>theData = NULL 您的进程可能会死于b> theData = NULL行
Also, you can statically declare your HashTable, either locally, or in some region high enough in the stack that the stack is non-ascending (in memory) while it is used and pass a pointer to the HashTable to your initialize function to avoid a malloc. 此外,您可以在本地或在堆栈中足够高的某个区域中静态声明您的HashTable,以确保在使用该堆栈时该堆栈不升序(在内存中),并将指向HashTable的指针传递给您的initialize函数,以避免malloc。 malloc is slow. malloc很慢。
So in main, you can do: 因此,总的来说,您可以执行以下操作:
HashTable table; HashTable表; InitializeHashTable(&table); InitializeHashTable(&table);
// use table (no need to free) // just do not return table //使用表(无需释放)//只是不返回表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.