2015-09-28 154 views
1

我正在通過cs50x課程,做拼寫檢查程序。在我的這個程序的第四個實現中,我遇到了malloc問題。 這次我決定實現一個二叉樹。 我已閱讀了很多有關此問題的線索,並多次查看了我的代碼,但我仍然無法理解我做錯了什麼。 問題出現在將字典加載到RAM中的遞歸函數中。Malloc聲明失敗C

#include <stdbool.h> 
#include <stdio.h> 
#include <math.h> 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 

#include "dictionary.h" 



// standart node of the trie 
typedef struct node 
{ 
    char word[LENGTH + 1]; 
    struct node* less; 
    struct node* more; 
} 
node; 

// Function definitions 
void unload_node(node* pr_node); 
void ld_bin_tree(int min, int max, node* node); 
bool check_word(char* lword, node* parent); 

// Global variables 
// root of the tree 
node* root; 
FILE* dict; 
//size of dictionary 
int dict_size = 0; 

bool load(const char* dictionary) 
{ 
    // open dictionary file 
    dict = fopen(dictionary, "r"); 
    int nwords = 0; 
    int min = 0; 
    int max = 0; 
    root = malloc(sizeof(node)); 

    //if file wasn't open 
    if(dict == NULL) 
    { 
     printf("Error opening ditionary file!"); 
     return false; 
    } 

    // tmp storage for read word 
    char buffer[LENGTH + 1]; 

    // count words in the dictionary 
    while(fscanf(dict, "%s", buffer) > 0) 
    { 
     nwords++; 
    } 
    max = nwords; 
    rewind(dict); 
    ld_bin_tree(min, max, root); 


    // close file 
    fclose(dict); 
    return false; 
} 
/* 
* Recursion function to fill in binary tree 
*/ 

void ld_bin_tree(int min, int max, node* node) 
{ 
    // tmp word holder 
    char buffer[LENGTH + 1]; 

    // next mid value 
    int mid = (min + max)/2; 

    // if mid == 0 then the bottom of the brunch reached, so return 
    if(max - min < 2) 
    { 
     if(min == 0) 
     { 
      fscanf(dict, "%s", node->word); 
      dict_size++; 
      return; 
     } 
     return; 
    } 

    // go through the dict to the mid string 
    for(int i = 0; i <= mid; i++) 
    { 
     fscanf(dict, "%s", buffer); 
    } 

    // fill in word 
    strcpy(node->word, buffer); 
    // go at the beginning of the dict 
    rewind(dict); 

    // fill in input node 
    // fill in new children nodes 
    struct node* new_node = malloc(sizeof(node)); 

    node->less = new_node; 

    // send lesser side 
    ld_bin_tree(min, mid, node->less); 

    new_node = malloc(sizeof(node)); 
    node->more = new_node; 
    // send greater side 
    ld_bin_tree(mid, max, node->more); 

    dict_size++; 
    return; 
} 

我試圖讓使用Valgrind的這個錯誤,但它給了我很多的警告關於閱讀和未分配的內存塊寫。但是因爲編程還不是很好,所以這個警告並沒有給我提供線索。

所以我要求更精確的幫助,如果有可能的話。先謝謝你。

的拼寫程序的其他部分可以在這裏找到: https://www.dropbox.com/sh/m1q1ui2g490fls7/AACnVhjjdFpv1J0mUUhY2uV2a?dl=0

回答

3

在功能ld_bin_tree()你有

struct node* new_node = malloc(sizeof(node)); 

這裏node是一個指針不struct node類型的對象。

你有

node *node;

所以node全局定義被覆蓋,這使得它的指針。

所以你沒有爲整個結構分配內存。你應該有

struct node* new_node = malloc(sizeof(struct node)); 
+2

啊,是的。 'node * node'是一個討厭的聲明,因爲它重新定義了'node'的含義。 –

+1

或者只是寫'malloc(sizeof(* new_node));'這會修復或暴露這樣的錯誤。 – Lundin