malloc 动态内存分配几个经典面试题

#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;
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值