VS2017 DLL动态库使用教程【三】动态内存管理

在dll内的malloc内存,必须在dll内free。否则就会出现问题。

比如:

DLL文件:

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

_declspec(dllexport) int* GetA(int size) //根据形参malloc出一个内存,并把它返回
{
	int *q = (int *)malloc(sizeof(int)*size); //这一行根据形参申请大小
	for (int i = 0; i < size; i++)  //这里根据形参依次赋值0,1,2,3,4........ 相信大家都看得的懂
	{
		q[i] = i;
	}
	return q;
}

DLLAPP文件(使用该dll的文件):

#include <iostream>
#include <Windows.h>
//声明库
#pragma comment(lib,"DLL_1.lib")
_declspec(dllexport) int* GetA(int size); //根据形参malloc出一个内存,并把它返回

int main()
{
	int *q = GetA(4); 
	for (int i = 0; i < 4; i++)
	{
		printf("%d\n", q[i]); //依次打印
	}
	free(q); //,这样释放是不可以的
	system("pause");
	return 0;
}

运行结果:

他运行到这里就已经卡住,并且无法关闭窗口,如果用之前的vs版本还可能弹出错报提示窗


正确的释放方式:

DLL文件

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

_declspec(dllexport) int* GetA(int size) //malloc出一个内存,并把它返回
{
	int *q = (int *)malloc(sizeof(int)*size);
	for (int i = 0; i < size; i++)
	{
		q[i] = i;
	}
	return q;
}
\\!!!!!!!!!!!!!!新加入的代码!!!!!!!!!!!!!
_declspec(dllexport) void freeA(int* i) //释放传入的指针
{
	free(i);
}
#include <iostream>
#include <Windows.h>
#include <mydll.h>
//声明库
#pragma comment(lib,"DLL_1.lib")
_declspec(dllexport) int* GetA(int size); //malloc出一个内存,并把它返回
_declspec(dllexport) void freeA(int *i);//释放

int main()
{
	int *q = GetA(4);
	for (int i = 0; i < 4; i++)
	{
		printf("%d\n", q[i]);
	}
	freeA(q); //使用DLL内释放函数
	system("pause");
	return 0;
}

没有任何错误,也没有卡住


注:new 和delete()也是一样,需要在dll内释放动态内存。

猜你喜欢

转载自blog.csdn.net/nullccc/article/details/80957423
今日推荐