堆区、栈区、常量区,以前迷迷糊糊,今天在一本书上算是看明白了。这点非常重要!
栈区:先说特点:“先进后出”,空间非常小,系统自己管理,随时使用、随时释放。像函数的形式参数,局部变量都是占用栈区。
void Stack(char **pp) {
char* temp = NULL;
}
堆区:你可以理解为内存,空间比较大,需要自己申请、自己释放,熟悉的malloc函数。
void Stack(char **pp) {
char* temp = NULL;
temp = malloc(sizeof(char) * 100);
}
常量区:就是一些字符、字符串所在空间,怎么理解呢?
int main() {
char* p = "hello world";
}
“p”,所在区,栈区,“hello world” ,所在区,栈区。但是。。。下面代码中“hello world”,在常量区。temp指向“”,所在地址区域。
void Stack(char **pp) {
char* temp = NULL;
temp = malloc(sizeof(char) * 100);
memset(temp, 0, 100);
strcpy(temp, "hello world");
}
图中“2”,是temp指向堆区的首地址。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void Stack(char **pp) {
char* temp = NULL;
temp = malloc(sizeof(char) * 100);
memset(temp, 0, 100);
strcpy(temp, "hello world");
*pp = temp;
}
int main() {
char* p = NULL;
Stack(&p);
printf("%s\n", p);
}
代码执行过程如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void Stack(char **pp) {
char* temp = NULL;
temp = malloc(sizeof(char) * 100);
memset(temp, 0, 100);
strcpy(temp, "hello world");
*pp = temp;
//printf("%p\n", temp);
}
int main() {
char* p = NULL;
//printf("%p\n", &p);
Stack(&p);
printf("%s\n", p);
if (p != NULL) {
free(p);
printf("释放空间结束\n");
p=NULL;
}
else
{
printf("未完成释放空间\n");
}
}