我正在尝试从控制台获取输入并将其添加到哈希表中。但是我得到了分段错误11。所以,我用gdb调试了程序。这表明我正在尝试使用指针变量访问我无法访问的内存。我认为这是显而易见的,但我错过了
这就是gdb正在显示的内容。
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000008
0x0000000100000986 in CreateHashTable (size=200) at hashing.c:29
29 h->Table[i]->next = NULL;这是代码
头文件:
#define LOAD_FACTOR 20
#define INITIAL_SIZE 200
struct HashTable *CreateHashTable(int size);
int HashSearch(struct HashTable *h,int data);
int HashInsert(struct HashTable *h,int data);
int HashDelete(struct HashTable *h, int data);
void Rehash(struct HashTable *h);
int Hash(int data, int size);
struct ListNode
{
int key;
int data;
struct ListNode *next;
};
struct HashTableNode
{
int bcount;
struct ListNode *next;
};
struct HashTable
{
int tsize;
int count;
struct HashTableNode **Table;
};实施文件:
#include "hashing.h"
#include<stdio.h>
#include<stdlib.h>
struct HashTable *CreateHashTable(int size)
{
struct HashTable *h;
h = (struct HashTable *) malloc ( sizeof(struct HashTable) );
if(h == NULL)
{
printf("Memory Error");
return NULL;
}
h->tsize = (int) size/LOAD_FACTOR;
printf("h->tsize = %d",h->tsize);
h->count = 0;
h->Table = malloc ( ( sizeof(struct HashTableNode **) ) * (h->tsize) );
if( h->Table == NULL )
{
printf("Memory Error");
return NULL;
}
int i;
for( i=0 ; i < (h->tsize) ; i++)
{
h->Table[i]->next = NULL;
h->Table[i]->bcount = 0;
}
return h;
}我会粘贴其余的文件,或驱动文件,但我不认为它相关。请告诉我为什么我要得到分割错误11
发布于 2014-09-02 06:42:05
您为指针数组分配了内存,但没有为该数组的成员分配内存。
for( i=0 ; i < (h->tsize) ; i++)
{
h->Table[i] = malloc(...); //put correct arguments here and check allocation
h->Table[i]->next = NULL;
h->Table[i]->bcount = 0;
}发布于 2014-09-02 06:37:52
你的问题是:
struct HashTableNode **Table;如果您想要一个节点数组(不是2d数组),请更改为:
struct HashTableNode *Table;也变了
h->Table = malloc ( ( sizeof(struct HashTableNode **) ) * (h->tsize) );至
h->Table = malloc(sizeof(struct HashTableNode) * h->tsize);我想我想要一个指向节点的指针数组,不是吗?
正如@WhozCraig所指出的那样,没有理由增加间接的影响。
示例A(指针):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *a; /* pointer */
int i, n = 10;
a = malloc(n * sizeof(int)); /* space for 10 ints */
for (i = 0; i < n; i++) {
a[i] = i;
}
for (i = 0; i < n; i++) {
printf("%d\n", a[i]);
}
free(a);
return 0;
}示例B(指针指向指针):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int **a; /* pointer to pointer*/
int i, n = 10;
a = malloc(n * sizeof(int *)); /* space for 10 pointer to ints */
for (i = 0; i < n; i++) {
a[i] = malloc(sizeof(int)); /* space for 1 int */
*a[i] = i;
}
for (i = 0; i < n; i++) {
printf("%d\n", *a[i]);
free(a[i]);
}
free(a);
return 0;
}正如您所看到的,两者都在做相同的事情,但是第一个操作所需的内存更少,代码也更简洁。
让人容易记住的一种方法是:
int *可以容纳一个数组
int **可以容纳一个表(NROWS * NCOLS)
int ***可以容纳一个表数组
https://stackoverflow.com/questions/25617108
复制相似问题