我在找出下面的代码有什么问题时遇到了问题。我运行了完整的代码,并做了很多输入测试,并且按照我的要求处理了错误。我还使用valgrind,cppchecker之类的东西来检查已修复错误的错误。然后,我决定使用afl-fuzzer对我的代码进行高级错误检测,由于下面的代码行,导致很多崩溃。但是,大多数崩溃是由于分段错误造成的。但我似乎看不出代码有什么问题。任何帮助将不胜感激。下面是不断给出错误的函数。我认为与sscanf
有关:
Tree* insert(char* command, Tree* tree) {
int age;
char* name = malloc(sizeof(char) * 20);
if (2 != sscanf(command, "i %d %20s", &age, name)){
fprintf(stderr, "Failed to parse insert command: not enough parameters filled\n");
// return NULL;
}
if (tree == NULL){
tree = tree_create();
}
tree_insert(tree, age, name);
return tree;
}
tree_create函数
Tree* tree_create(){
Tree *tree = malloc(sizeof(Tree));
tree->root = NULL;
return tree;
}
tree_insert
void tree_insert(Tree* tree, int age, char* name) {
if (tree->root == NULL) {
Node *node = calloc(1, sizeof(Node));
node->name = name;
node->age = age;
node->isRoot = true;
node->right = NULL;
node->left = NULL;
tree->root = node;
} else {
node_insert(tree->root, age, name, 1);
}
}
主要问题在各行:
char* name = malloc(sizeof(char) * 20);
if (2 != sscanf(command, "i %d %20s", &age, name)){
您的转换规范%20s
说sscanf()
可以在name
中存储20个字符和一个空字节,但是您只为19个字符和一个空字节分配了足够的空间。 scanf()
系列功能与大多数其他功能之间的“一对一”会引起问题,而模糊处理人员应该找到它们。
解决方法很简单:将第一个20更改为21或将第二个20更改为19。更好的方法是您的判断。我们没有足够的信息来选择哪个(如果有的话)是更好的选择。