Node *addToTree(Node *head, Node *newNode) {
if (head == NULL) {
head = newNode;
} else {
if (newNode->price < head->price) {
head->left = addToTree(head->left, newNode);
} else
if (newNode->price > head->price) {
head->right = addToTree(head->right, newNode);
} else
if (newNode->price == head->price) {
free(newNode);
}
}
return head;
}
Node *getCars(char *name) {
FILE *fp;
if ((fp = fopen(name, "r")) == NULL) {
return NULL;
} else {
Node *head = NULL;
Node *tmp;
char delim[2] = "|";
char car[MAXLINELENGTH] = {0};
char *token = NULL;
int ch;
while (!feof(fp)) {
tmp = malloc(sizeof(Node));
tmp->left = tmp->right = NULL;
fgets(car, MAXLINELENGTH, fp);
token = strtok(car, delim);
while (token != NULL) {
if (strcmp(token, "model") == 0) {
token = strtok(NULL, delim);
strcpy(tmp->model, token);
} else
if (strcmp(token, "make") == 0) {
token = strtok(NULL, delim);
strcpy(tmp->make, token);
} else
if (strcmp(token, "price") == 0) {
token = strtok(NULL, delim);
tmp->price = atoi(token);
} else
if (strcmp(token, "year") == 0) {
token = strtok(NULL, delim);
tmp->year = atoi(token);
} else
if (strcmp(token, "color") == 0) {
token = strtok(NULL, delim);
strcpy(tmp->color, token);
} else
if (strcmp(token, "type") == 0) {
token = strtok(NULL, delim);
if (token == NULL) {
break;
}
strcpy(tmp->type, token);
} else
if (strcmp(token, "mileage") == 0) {
token = strtok(NULL, delim);
tmp->mileage = atoi(token);
}
token = strtok(NULL, delim);
}
if (check("makes.txt", tmp->make) != 1) {
continue;
} else
if (check("colors.txt", tmp->color) != 1) {
continue;
} else
if (check("types.txt", tmp->type) != 1) {
continue;
} else {
head = addToTree(head, tmp);
}
}
free(tmp);
fclose(fp);
return head;
}
}
所以對於一個家庭作業,我應該通過輸入文件與汽車10000左右的信息是,型號解析,顏色,型號,價格,行駛里程和年並根據它們的價格將它們輸入到BST中,當我運行代碼時,它說我在malloc的tmp指針處有274個字節丟失。我只是想知道這是什麼解決方案,而且我真的可以解析任何建議/幫助因爲我的getCars功能是醜陋的,它也需要大約15秒的時間運行,任何幫助,非常感謝!泄漏的內存,同時創造BST,解析需要援助
變化'而{'來'而(與fgets(汽車,MAXLINELENGTH,FP)){'刪除'免費(FEOF(FP)!) (tmp);' – BLUEPIXY
@BLUEPIXY你會不會也知道爲什麼在valgrind中獲得「有條件的跳轉取決於未初始化的值」錯誤?或者你會看到更多的代碼? –
'continue;' - >'free(tmp);繼續;' – BLUEPIXY