#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
//
//void test() {
// int i;
// int* ptr = (int*) malloc (10*sizeof(int));
// if(NULL == ptr) {
// exit(EXIT_FAILURE);
// }
// //越界了 在堆里面
// for(i = 0;i<=10;i++) {
// *(ptr+i) = i;
// }
// free(ptr);
//}
//void test() {
// int a = 10;
// //int a 存放在静态区
// int *ptr = &a;
// //对于非静态内存使用了free 函数
// free(ptr);
//}
//void test( ) {
// int *ptr = (int *)malloc (sizeof (int));
// ptr++;
// //ptr 不在指向起始的位置,而 free 函数必须指向开辟内存的起始位置
// free(ptr);
//}
//void test (){
// int *ptr = (int*)malloc (100);
// free(ptr);
// //重复释放
// free(ptr);
//}
//void Getmemory(char **ptr) { //那么就得是一个二级指针
// *ptr = (char *)malloc(100);
//}
//void test() {
// char *str = NULL;
// //形参是实参的拷贝,所以执行完下面的代码之后并不会影响 str 的地址,
// //还是一个空指针
// //只有传进去地址之后才可以
// Getmemory (&str);
// if(str == NULL) {
// return ;
// }
// strcpy(str,"hello world");
// printf(str);
// free(str);
//}
//char *GetMemory(void) {
// //是一个局部变量(字符数组,并不是地址)在运行完就消失了
// //生命后期是当前代码块
// //所以返回之后打印的是未知的,因为访问了非法内存空间;
// char p[] = "hello world";
// return p;
// }
//test () {
// char *str = NULL;
// str = GetMemory ();
// printf(str);
//}
//void Getmemory (char **str,int num) {
// *str = (char*)malloc (num);
//}
//void test (){
// char *str = NULL;
// Getmemory (&str,100);
// if(str == NULL) {
// return ;
// }
// strcpy (str,"hello world");
// printf(str);
// free (str);
//}
void test () {
char *str = (char*)malloc (100);
strcpy(str,"hello world");
printf(str);
free(str);
//释放掉之后是一个野指针,不能用的
//因为指不定会被系统用掉
//你现在能用,以后操作系统可能还会分配给其他
if(str!= NULL) {
strcpy(str,"hello world");
printf(str);
}
}
int main () {
////申请500MB内存,申请的内存过大是可能会失败的
//int *ptr =(int*)malloc(INT_MAX/4);
//*ptr = 20;
//printf("%d\n",*ptr);
//free(ptr);
//ptr = NULL;
test ();
return 0;
}
malloc 动态内存分配几个经典面试题
猜你喜欢
转载自blog.csdn.net/weixin_44077227/article/details/89404407
今日推荐
周排行