char* test_stack(){
char str_stack[] = "hello";//栈区
return &str_stack; // 返回地址时,数据被销毁了
}
char* test_static(){
static char str_static[] = "hello";// 静态区
return &str_static;// 返回地址并且数据还在
}
char* test_heap(){
char* str_heap = (char*)malloc(15 * sizeof(char));
strcpy(str_heap, "hello return");
return str_heap;
}
int main(){
// 访问栈区
char* p_char = test_stack();
printf("%s\n", p_char);// 非法访问内存,打印乱码
// 访问静态区 ,静态局部变量的生命期为整个源程序
char* p_static = test_static();
printf("%s\n", p_static);//hello
// 访问堆区 , 堆区的空间只有free后才会被释放
char* p_malloc = test_heap();
printf(p_malloc);//hello return
free(p_malloc);
p_malloc = NULL;
}
C语言非法访问内存知识点
最新推荐文章于 2024-09-10 20:34:55 发布