【C】103.动态内存函数的使用

动态内存函数的使用

malloc函数和free函数

#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main() {
	int* p = (int*)malloc(INT_MAX);
	//int* p = (int*)malloc(10 * sizeof(int));
	if (p == NULL) {
		printf("%s\n", strerror(errno));
	}
	else {
		int i = 0;
		for (i = 0; i < 10; i++) {
			*(p + i) = i;
		}
		for (i = 0; i < 10; i++) {
			printf("%d ", *(p + i));
		}
	}

	//释放空间
	free(p);
	return 0;
}

calloc函数

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main() {
	int* p = (int*)calloc(10, sizeof(int));
	if (p == NULL) {
		printf("%s\n", strerror(errno));
	}
	else {
		int i = 0;
		for (i = 0; i < 10; i++) {
			printf("%d ", *(p + i));
		}
	}
	return 0;
}

realloc函数

#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main() {
	int* p1 = (int*)malloc(20);
	if (p1 == NULL) {
		printf("%s\n", strerror(errno));
	}
	else {
		int i = 0;
		for (i = 0; i < 5; i++) {
			*(p1 + i) = i;
		}
	}
	int* p2 = (int*)realloc(p1, 40);
	if (p2 != NULL) {
		p1 = p2;
	}
	int i =0;
	for (i = 0; i < 10; i++) {
		printf("%d ", *(p1 + i));
	}
	//释放内存
	free(p1);
	p1 = NULL;
	return 0;
}

题目1:

void getmemory(char* p) {
	p = (char *)malloc(100);
}
void test(void) {
	char* str = NULL;
	getmemory(str);
	strcmp(str, "hello world");
	printf(str);
}
int main() {
	test();
	return 0;
}

该程序正确吗?若不正确,说明原因
1.运行代码程序会出现崩溃的现象
2.程序存在内存泄漏的问题(str以值传递的形式给p,p是getmemory函数的形参,只能函数内部有效,等getmemory函数返回之后,动态开辟内存尚未释放,并且无法找到,所以会造成内存泄漏)

改正1:

void getmemory(char**p) {
	*p = (char *)malloc(100);
}
void test(void) {
	char* str = NULL;
	getmemory(str);
	strcmp(&str, "hello world");
	printf(str);
	free(str);
	str=NULL;
}
int main() {
	test();
	return 0;
}

改正2:

char * getmemory(char* p) {
	p = (char *)malloc(100);
	return p;
}
void test(void) {
	char* str = NULL;
	str=getmemory(str);
	strcmp(str, "hello world");
	printf(str);
	free(str);
	str=NULL;
}
int main() {
	test();
	return 0;
}

题目2:

char* getmemory() {
	char p[] = "hello world";
	return p;
}
void test() {
	char* str = NULL;
	str = getmemory();
	printf(str);
}
int main() {
	test();
	return 0;
}

该程序正确吗?若不正确,说明原因
不正确;因为会出现非法访问的问题,p指向的字符串只在函数内部存在,一出函数,这部分就不存在了。(涉及返回栈空间的地址问题)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值