13-指针和动态内存-内存泄漏
一、视频笔记:
C语言通过malloc,来获取堆上的内存。
动态调用内存: malloc 和 free ;new 和 delete 都行。
内存泄漏指的是我们动态申请了内存,但是即是是使用完了之后(从来都不去释放它)。只会由不正确的动态内存(堆)的使用引起。
每个函数调用都对应一个栈帧。
任何未使用和未引用的堆上内存都是垃圾。
JAVA 和C+上,堆上的垃圾会被自动回收。
内存泄漏是不当的使用动态内存或内存的堆区,在一段时间内持续增长。
总是因为堆中,未使用或未引用的内存块才会发生。栈上的会自动回收,栈的大小固定,最多会栈溢出。
函数调用结束的时候,它的所有的局部变量都会被清除。
栈区:静态或全局变量——没有在函数内部声明,生命周期是整个程序的执行期间。一个区段是用来存放函数调用和局部变量的。
代码区、全局区、栈区是固定的在编译期间就决定了。
第四个区段称为堆或动态内存区:不是固定的,堆可以动态按需生长。
Srand(time(NULL));根据时间变化给出随机值。
二、测试代码:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h> // 包含字符串处理函数库
#include <math.h>
#include <time.h>int cash = 100;
void Play(int bet) {char* C = (char*)malloc(10000 * sizeof(char));C[0] = 'J'; C[1] = 'Q'; C[2] = 'K';printf("Shuffling...\n");srand(time(NULL));int i;for (i = 0; i < 5; i++){int x = rand() % 3;int y = rand() % 3;int temp = C[x];C[x] = C[y];C[y] = temp;}int playersGuess;printf("What't the position of queen - 1,2 or 3?");scanf_s("%d", &playersGuess);if (C[playersGuess - 1] == 'Q') {cash += 3 * bet;printf("You Win ! Result = \"%c %c %c\" Total Cash = $% d\n", C[0], C[1], C[2], cash);}else {cash -= bet;printf("You Loose ! Result = \"%c %c %c\" Total Cash = $% d\n", C[0], C[1], C[2], cash);}free(C);
}int main()
{int bet;printf("**Welcome to the Virtual Casion**\n\n");printf("Total cash = $%d\n", cash);while (cash > 0) {printf("What's your bet? $");scanf_s("%d", &bet);if (bet == 0 || bet > cash) break;Play(bet);printf("\n**********************\n");}
}