簡體   English   中英

返回指向函數中分配的結構的指針

[英]Returning a pointer to a structure malloc'ed in a function

我正在使用一個函數來為哈希函數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;
}

我的程序可以使用-pedantic -Wall干凈地編譯,但是存在段錯誤。 使用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) 

具有結構“ Bucket”定義的標頭部分:

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

這是范圍問題嗎? 函數完成后,它會殺死我分配的內存還是什么?

平台是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;
}

}

這行:

if (!table[hashkey]->text)

應該:

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

並且類似地在以下幾行。 在這個函數中, table實際上是一個指針,指向被稱為可變hashTablemain

解決此錯誤的另一種方法是使函數采用Bucket * ,而不傳遞hashTable的地址。 該函數似乎不需要知道hashTable的地址,因為它僅將內容放入表中。

我試圖重現此問題,但未能成功。

因此,我唯一的猜測是您可能已省略了向主模塊提供正確的函數簽名的過程,因此將其稱為int createHashTable() 這將導致警告,並使您丟失結果指針IFF的高32位,而您擁有64位指針和32位int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM