讨论/题目交流/#429 N叉树的层序遍历,谁能告诉我如下代码怎么错了嘛??/
#429 N叉树的层序遍历,谁能告诉我如下代码怎么错了嘛??

报下面的错。。。。很疑惑

=================================================================
==45==ERROR: AddressSanitizer: attempting free on address which was not malloc()-ed: 0x7ffc551302c0 in thread T0
#0 0x7fb8adeccc7f in __interceptor_free (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10bc7f)
#2 0x7fb8aceb182f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
Address 0x7ffc551302c0 is located in stack of thread T0 at offset 496 in frame
This frame has 6 object(s):
[32, 36) 'n'
[96, 100) 'ret_size'
[160, 168) 'nbytes'
[224, 232) 'line'
[288, 296) 'ret_colsize'
[352, 356) 'SEPARATOR' <== Memory access at offset 496 overflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
(longjmp and C++ exceptions are supported)
SUMMARY: AddressSanitizer: bad-free (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x10bc7f) in __interceptor_free
==45==ABORTING

typedef struct Node Node;

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

void dfs(Node* node, int level, int** ans, int* rowSize, int** returnColumnSizes) {
    if (!node) return;
    if (level == *rowSize) {
        ans[(*rowSize)++] = malloc(1000 * sizeof(int));
        (*returnColumnSizes)[level] = 0;
    }

    ans[level][(*returnColumnSizes)[level]++] = node->val;
    for (int i = 0; i < node->numChildren; i++)
        dfs(node->children[i], level + 1, ans, rowSize, returnColumnSizes);
}

int** levelOrder(Node* root, int* returnSize, int** returnColumnSizes) {

    int** ans = malloc(1000 * sizeof(int*));
    int rowSize = 0;

    dfs(root, 0, ans, &rowSize, returnColumnSizes);

    *returnSize = rowSize;
    return ans;
}
展开讨论
王小强发起于 2020-05-15
最近编辑于 2020-05-15

看一下题目说明
Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().

returnColumnSizes 是一个返回参数,是一个指向指针的指针.你需要 malloc 一个数组,里面包含数组各个 Column 的长度

int *columnSizes = malloc(...) // 里面存各个 column 的长度
...
returnColumnSizes = &columnSizes;

更新:上面不对,应当是

int *columnSizes = malloc(...) // 里面存各个 column 的长度
...
*returnColumnSizes = columnSizes;