我仍然无法理解为什么这里仍然存在内存泄漏,因为strdup
(这是错误的说法),我确保在删除节点之前释放了strdup
的所有分配的内存,并在程序结束时释放了所有节点。我错过了什么?
下面是我写的代码:
struct background_processes *head = NULL;
struct background_processes {
int pid;
char *cmd_name;
struct background_processes *next;
};
// Add a background process to the Background processes LinkedList
void add_background_process(int pid, char *name) {
if (head == NULL) {
head = malloc(sizeof(struct background_processes));
if (head == NULL) {
exit(EXIT_FAILURE);
}
head->pid = pid;
head->cmd_name = strdup(name);
head->next = NULL;
} else {
struct background_processes *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = malloc(sizeof(struct background_processes));
if (current->next == NULL)
exit(EXIT_FAILURE);
current->next->pid = pid;
current->next->cmd_name = strdup(name);
current->next->next = NULL;
}
}
// Remove a background process from the Background processes LinkedList
void remove_background_process(int pid) {
struct background_processes *current = head;
struct background_processes *prev = NULL;
while (current != NULL) {
/* If the process is running */
if (pid == current->pid) {
if (current == head) {
head = head->next;
free(current->cmd_name);
free(current);
current = head;
} else {
prev->next = current->next;
free(current->cmd_name);
free(current);
current = prev->next;
}
} else {
prev = current;
current = current->next;
}
}
}
void free_linkedlist() {
struct background_processes *current = head;
struct background_processes *after;
while (current != NULL) {
after = current->next;
free(current->cmd_name);
free(current);
current = after;
}
}
int main() {
// Some code
while (1) {
// Some other code
execute_pipeline(l);
}
// Freeing all allocated memory
free_linkedlist();
}
字符串
我很感激你的帮助。谢谢!
1条答案
按热度按时间acruukt91#
在发布的代码中没有可见的泄漏。问题一定在其他地方:
strdup()
分配内存并泄漏内存。cmd_name
字段。建议避免重复分配和解除分配代码。
以下是修改后的版本:
字符串