Malloc取消先前分配的指针?

时间:2018-11-24 22:48:29

标签: c pointers malloc

我目前正在为一个学校项目构建一个二进制搜索树,并遇到一个小问题:

正在调用一个函数(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;
}

和structure / typedefs:

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

1 个答案:

答案 0 :(得分:3)

您的代码没有按照您的想法分配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;
    ...
  }