返回指向函数中的结构malloc的指针

时间:2014-12-07 20:59:49

标签: c function pointers scope malloc

我使用malloc函数并为哈希函数初始化一些内存,如下所示:

int main (int argc, char * argv [])
{
  Bucket * hashTable;
  hashTable = createHashTable();
  ...

在' main.c'

在另一个文件中调用的函数是:

Bucket * createHashTable()
{
  Bucket * hashTable = malloc ( sizeof(Bucket) * HASHSIZE);
  int c=0;
  for (c=0;c<HASHSIZE;c++)
  {
    hashTable[c].key=NULL;
    hashTable[c].text=NULL;
    hashTable[c].next=NULL;
  }
  return hashTable;
}

我的程序使用&#39; -pedantic -Wall&#39;干净利落地编译,但是段错误。使用gdb,我得到了这个:

Reading symbols from hash...done.
(gdb) break 11
Breakpoint 1 at 0x400990: file main.c, line 11.
(gdb) run
Starting program: /home/user/Projects/random/hash 

Breakpoint 1, main (argc=1, argv=0x7fffffffdf78) at main.c:11
11    hashTable = createHashTable();
(gdb) print hashTable
$1 = (Bucket *) 0x400520 <_start>
(gdb) print * hashTable
$2 = {
key = 0x89485ed18949ed31 <error: Cannot access memory at address 0x89485ed18949ed31>, 
text = 0x495450f0e48348e2 <error: Cannot access memory at address
0x495450f0e48348e2>,    next = 0xc74800400a90c0c7}
(gdb) 

带结构的标题部分&#34; Bucket&#34;定义:

typedef struct bucket{
  char * key;
  char * text;
  struct bucket * next;
} Bucket;

这是范围问题吗?功能完成后,是否会杀死我的malloc内存或什么?

平台是64位Linux,这次从malloc()返回的地址是0x1665010 - 我想如果它失败了,它将是NULL。

编辑:此后的下一个函数,在main.c中,尝试向表中添加一个条目:

printf("Adding banana...\n");
addItem("Banana", "Bananas are yellow", &hashTable);
<是的(是的,是的 - 香蕉,我知道)功能是:

void addItem(char * key, char * data, Bucket ** table)
{
  unsigned int hashkey;
  hashkey=hash(key);
  printf("%lu\n",strlen(key));
if (!table[hashkey]->text) /* SEGFAULTS HERE */
{
  table[hashkey]->key=key;
  table[hashkey]->text=data;
}
else
{
  Bucket * newListElement = malloc(sizeof(Bucket));
  newListElement->key=key;
  newListElement->text=data;
  newListElement->next = NULL;
  table[hashkey]->next = newListElement;
}

}

2 个答案:

答案 0 :(得分:1)

这一行:

if (!table[hashkey]->text)

应该是:

if ( !(*table)[hashkey]->text )

以及类似的以下几行。在此函数中,table实际上是指向hashTable中名为main的变量的指针。

修复此错误的另一种方法是使函数执行Bucket *,而不传递hashTable的地址。似乎没有必要让函数知道hashTable的地址,因为它只是把事情放在表格中。

答案 1 :(得分:0)

我试图重现这个问题,但无法成功。

所以我唯一的猜测是你可能已经省略了向主模块提供正确的函数签名,并且它被称为int createHashTable()。这应该会导致警告,并且会使您丢失结果指针IFF的高32位,您有64位指针和32位int

相关问题