c - C 中的树遍历和串联崩溃

标签 c string pointers memory

有一个随机树生成器,我必须根据子遍历连接树的值。例如,如果我有

com ----- org------net---
           |
           mom---dad---son
                        |
                       good

我想要字符串“goodsonorg”

struct trie_node *going = root;   // this gets the root of the tree
char* joiner = NULL;             //using this to join the previous part

char *lastOne = (char *)(malloc(going->strlen+1000)); //setting safe buffer

while(going->next != NULL || going->children != NULL) {

    while(going->next){         // always go as right as possible
        going = going->next;
    }

    if(going->children){      //traverse down to child

        if(joiner == NULL) { // traverse from root (previous will be null)

             printf(" first key is: \n");
             joiner = (char *)(malloc(going->strlen)+100);
             strncpy(joiner,going->key, going->strlen+1);       
             puts(joiner);
        }

        else{
            printf(" \n We need to concatenate: \n");
            going = going->children; // go down

            strncpy(lastOne, going->key, going->strlen); // get the current key in last
            puts(lastOne);
            printf(" with the previous one to get: \n ");
            strcat(lastOne, joiner); // attach the joiner to it.

            strncpy(joiner, lastOne, strlen(joiner)+strlen(lastOne)); // then update the joiner
            puts(lastOne);
            }

在这个代码块的末尾,我应该在 lastOne 中有我的连接字符串,但是由于某种原因我得到了一个段错误。我不确定为什么。我正在分配安全的大问题,因为 realloc 给我错误。有什么明显的我在这里失踪了吗?树遍历绝对有效。

最佳答案

malloc(going->strlen)+100 有问题。您正在使用 malloc() 从堆中获取一个地址,然后出于某种原因将 100 添加到该地址,并显式强制转换它以强制其工作。 (我建议查看 Do I cast the result of malloc? 。)这样的指针运算没有意义。这肯定会导致你以后在错误的地方读取或写入,导致段错误。

与其猜测适当的字符串分配大小应该是多少,不如跟踪它有多大,并根据需要扩展它(参见 realloc() )。

关于c - C 中的树遍历和串联崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40956190/

相关文章:

c++ - accept后如何判断正在使用的IP地址?

比较文本文件中的字符串的一行,并在找到时删除该行

c - 如何读取文件并将每个读取的行拆分为变量或数组

r - 转换已解析字符串的编码

c++ - 为什么这两种情况给出相同的结果?

pointers - ARM:如何处理堆栈指针?

c - 内存分配和动态内存分配

比较来自 2 个数组中任何元素的单词

JavaScript - 有没有办法检查字符串是否包含关键字但仅包含该关键字?

c - 在内存中分配的修改后的结构在函数结束后不保留值