我将缓冲区作为文件中的长字符串。然后我将逐字逐句添加到二叉树中作为节点。
如果我在不再使用缓冲区时尝试释放缓冲区,则会出现分段错误。Valgrind 指出了很多“Invalid read of size 1”错误。
如果我把它移到我的清洁支架上。它有效,但我遇到了严重的内存泄漏(因为程序可以读取更多文件)。
if (argc < 2) {
printf("No arguments was passed to proccess.\n");
return EXIT_SUCCESS;
} else {
for (int i = 1; i < argc; i++) {
FILE *file = openFile(argv[i]);
if (file != NULL) {
validFiles++;
// Get size of file and setting up a buffer
int fileSize = getFileSize(file);
buffer = calloc(fileSize + 1, sizeof(char));
fread(buffer,sizeof(char),fileSize,file);
fclose(file);
// Break down the buffer into a tree of nodes
pch = strtok (buffer,delimiters);
while (pch != NULL) {
root = insert(root, pch, argv[i], 1);
pch = strtok (NULL, delimiters);
} // free(buffer); should be here
}
}
}
if (validFiles > 0) {
searchBook(root);
freeTree(root);
free(buffer); // Only frees one of the buffers when multiple files are sent in
}
每个节点都会在树插入函数中为自己分配内存。