c-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;
}

和结构/类型定义:

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/d5LRsLVhttps://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;
...
}

相关内容

  • 没有找到相关文章

最新更新