出栈 不能释放堆区内存的问题
本帖最后由 zhenhaowa66 于 2021-11-6 11:14 编辑#define _CRT_SECURE_NO_WARNINGS
#include<time.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
#include<windows.h>
//链表的结构
typedef struct Node {
int data;
struct Node* pNext;
}NODE,* PNODE;
//栈的结构设计
typedef struct Stack {
PNODE pTop;
PNODE pBottom;
int Size;
}STACK,*PSTACK;
void init_Stack(PSTACK pS) {//初始化栈
PNODE pNode = malloc(sizeof(NODE));
pNode->data = 0;
pNode->pNext = NULL;
pS->pTop = pNode;
pS->pBottom = pS->pTop;
pS->Size = 0;
return;
}
void push_Stack(PSTACK pS,int data) {//数据进栈
PNODE pew = malloc(sizeof(NODE));
pew->data = data;
pew->pNext = pS->pTop;
pS->pTop = pew;
pS->Size++;
return;
}
int pop_Stack(PSTACK pS, int* vaue) {
if (pS->Size == 0) {
printf("栈是空的,出栈失败!\n");
return false;
}
else {
PNODE pf = pS->pTop;
pS->pTop = pf ->pNext;
vaue = pf->data;
free(pf);
pf = NULL;
pS->Size--;
printf("出栈元素是:%d\n",vaue);
return true;
}
}
void traverse_Stack(PSTACK pS) {
if (pS->Size == 0) {
printf("栈是空的!\n");
return;
}
PNODE pf = pS->pTop;
while (pf != pS->pBottom) {
printf("%d ", pf->data);
pf = pf->pNext;
}
return;
}
void test01() {
srand((unsigned int)time(NULL));
STACK S;
init_Stack(&S);
int len = 10;
int a = 0;
for (int i = 0; i < len; i++) {
push_Stack(&S, a = rand());
}
traverse_Stack(&S);
printf("\n");
printf("___________________________________\n");
int vaue = 0;
pop_Stack(&S,&vaue);
traverse_Stack(&S);
printf("\n");
printf("___________________________________\n");
}
int main() {
clock_t t_start, t_end;
t_start = clock();
test01();
t_end = clock();
printf("程序运行了:%d 毫秒!\n", t_end - t_start);
struct tm* sysTime;
time_t nowTime;
time(&nowTime);
sysTime = localtime(&nowTime);
printf("系统日期:%d-%d-%d\n", 1900 + sysTime\
->tm_year, sysTime->tm_mon + 1, sysTime->tm_mday);
printf("系统时间:%d-%d-%d\n", sysTime\
->tm_hour, sysTime->tm_min, sysTime->tm_sec);
}
程序运行到free(pf); 报错 Debug Error!
//free(pf); 后可以正常运行,大佬们给看看有什么问题,非常感谢!
//free(pf); 后运行输出如下:
3282 995 2479 24131 23307 475 17319 13577 16797 16021
___________________________________
出栈元素是:3282
995 2479 24131 23307 475 17319 13577 16797 16021
___________________________________
程序运行了:2 毫秒!
系统日期:2021-11-5
系统时间:23-51-24
请按任意键继续. . .
忘了说,编译器是VS2019已经找到原因了,也改好啦,现在可以正常运行了 已经找到原因了 {:5_95:}也改好了
页:
[1]