添加动态内存释放操作
时间: 2023-07-08 19:12:12 浏览: 55
在使用动态内存分配函数(如`malloc`)分配内存时,为了避免内存泄漏,我们需要在程序结束时手动释放这些内存。在栈的例子中,我们需要释放每个节点的内存。
下面是一个添加动态内存释放操作的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
typedef struct stack {
Node* top;
} Stack;
Stack* createStack() {
Stack* s = (Stack*)malloc(sizeof(Stack));
s->top = NULL;
return s;
}
void push(Stack* s, int data) {
Node* n = (Node*)malloc(sizeof(Node));
n->data = data;
n->next = s->top;
s->top = n;
}
int pop(Stack* s) {
if (s->top == NULL) {
printf("Stack is empty!\n");
return -1;
}
int data = s->top->data;
Node* temp = s->top;
s->top = s->top->next;
free(temp);
return data;
}
void traverse(Stack* s) {
Node* current = s->top;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
void destroyStack(Stack* s) {
Node* current = s->top;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
free(s);
}
int main() {
Stack* s = createStack();
push(s, 1);
push(s, 2);
push(s, 3);
traverse(s);
printf("%d\n", pop(s));
printf("%d\n", pop(s));
traverse(s);
push(s, 4);
traverse(s);
destroyStack(s);
return 0;
}
```
在该代码中,我们添加了一个`destroyStack`函数,用于释放栈中每个节点的内存。在该函数中,我们首先使用一个指针`current`来指向栈顶节点,然后循环遍历链表中的每个节点,释放每个节点的内存。最后,我们释放整个栈的内存。
在main函数中,我们在程序结束时调用`destroyStack`函数来释放栈的内存。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)