Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
我目前正在为学校项目构建二进制搜索树,遇到一个小问题:

调用一个函数(key_gen)为由一对字符串组成的节点生成一个密钥。这对于前两个节点工作正常;但是,在第三次调用key_gen时,第二个节点中包含的密钥将变为空。有人可以解释为什么吗?这是我的功能:

void main(){
    BStree tst = bstree_ini();
    bstree_insert(tst,key_gen("a","a"),data_gen(1));
    bstree_insert(tst,key_gen("c","c"),data_gen(2));
    key_gen("b","b"); //Upon execution, the key generated from key_gen("c","c") goes null
}

BStree bstree_ini(){
    BStree toReturn;
    BStree_node *toAllocate =(BStree_node *)malloc(sizeof(BStree_node));
    toAllocate = NULL;
    toReturn = &toAllocate;
    return toReturn;
}

Key key_gen(char *skey1, char *skey2){
    Key toReturn;
    toReturn = (Key_Struct*)malloc(sizeof(Key_Struct));
    toReturn->skey1 = string_dup(skey1);
    toReturn->skey2 = string_dup(skey2);
    return toReturn;
}

char * string_dup(char *str){
   char *toReturn = malloc(sizeof(char)*(strlen(str)+1));
   for(int i = 0; i<strlen(str)+1; i++){
       *(toReturn+i) = *(str+i);
   }
   return toReturn;
}

Data data_gen(int idata){
    Data toReturn;
    toReturn = (int *)malloc(sizeof(Data));
    *toReturn = idata;
}


和结构/ typedef:

typedef int* Data;

typedef struct {char *skey1;char *skey2;} Key_Struct;

typedef Key_Struct* Key;

typedef struct BStree_node{
Key key;
Data data;
struct BStree_node *left, *right;
} BStree_node;

typedef BStree_node** BStree;


我认为问题不在于插入,因为我的调试器显示所有变量均符合预期,直到调用key_gen(“ b”,“ b”)为止,但是如果需要,我可以提供插入代码。

先感谢您

编辑:

我添加了图片以帮助澄清问题
https://ibb.co/d5LRsLV
https://ibb.co/vCNKsNh

最佳答案

您的代码没有按照您的想法分配BStree。这里是问题:

BStree bstree_ini(){
    BStree toReturn;
    BStree_node *toAllocate =(BStree_node *)malloc(sizeof(BStree_node));
    // Next line: you leak the memory allocated,
    // and replace it with NULL yourself.
    toAllocate = NULL;
    // Next line: the address of the pointer toAllocate is a local stack
    // address and will cease to be valid once the routine returns.
    // (even though, if you allocated memory properly, you could return that)
    toReturn = &toAllocate;
    return toReturn;
}


你应该试试:

BStree_node bstree_ini(){
    return calloc(1, sizeof(BStree_node));
}


然后在main()中(main必须返回int btw):

  int main(void) {
    BStree_node tstnode = bstree_ini();
    BStree = &tstnode;
    ...
  }

10-07 23:25