The following code runs for a second and then a runtime error is caused by node->data = *data;
Node *TreeCreate(int level, const char *data)
{
Node *node = malloc(sizeof(node));
if (node != NULL) {
node->data = *data;
}
if (level != 0) {
node->leftChild = TreeCreate(level - 1, data + 1);
node->rightChild = TreeCreate(level - 1, data + (int)pow(2, level - 1));
}
return node;
}
Even if you reserved at least pow(2, level) characters for the string referenced by *data the next TreeCreate() call just fall off these boundaries:
TreeCreate(level, data) //-->
TreeCreate(level, data + 1) //--> ...
TreeCreate(level, data + pow(2, level-1) // -->
TreeCreate(level, data + pow(2, level-1) + 1) //--> well still may fit to you string
TreeCreate(level, data + pow(2, level-1) + pow(2, level-2) // --> may not fit
For example, level = 4, size of the string pointed by data = 16, when walking down the TreeCreate() call tree for leftChild will result in: data + 4 + pow(2, 3) + pow(2, 2) + pow(2, 1) --> data + 18 (!!)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.