malloc 和 free 可以用在动态库 而不能 用在静态库吗?

baidu_28726667 2018-08-16 10:47:18
没很了解书中的描述。书中这段代码中函数里面没有提供free方法,返回的只有句柄。按照书中描述是动态库的时候可以free掉? 而静态库不可以? 为何呢?!
...全文
278 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
实际上,malloc和free的方法自己可以模拟。
比如,最傻的,自己做一个没有任何优化的64k内存池。

#include <map>
#include <string>
using namespace std;
const int MAX_BLOCKS = 256;
const int TOTAL_SIZE = 65536;
char buf[TOTAL_SIZE];
int ptr_alloced[MAX_BLOCKS];
int b_used[MAX_BLOCKS];
int cur_top = 0;
int currBlocks = 0;
char * my_malloc(int size)
{
int insert_pos = currBlocks;
//寻找可用的块
for (int i = 0; i<currBlocks && insert_pos==currBlocks; ++i)
{
if (b_used[i]==0)
{
if (i < currBlocks - 1)
{
if (ptr_alloced[i + 1] - ptr_alloced[i] >= size)
insert_pos = i;
}
}
}
if (insert_pos == currBlocks)
{
if (cur_top + size > TOTAL_SIZE)
return 0;
cur_top += size;
ptr_alloced[insert_pos] = cur_top;
}
b_used[insert_pos] = 1;

++insert_pos;
if (insert_pos > currBlocks)
currBlocks = insert_pos;

return &buf[ptr_alloced[insert_pos - 1]];
}
void my_free(const char * ptr)
{
int del = -1;
for (int i = 0; i<currBlocks; ++i)
{
if (ptr_alloced[i] + buf == ptr)
{
del = i;
break;
}
}
if (del >= 0)
b_used[del] = 0;

}

int main()
{
char * p1 = my_malloc(1024);
char * p2 = my_malloc(2048);
char * p3 = my_malloc(1024);

my_free(p2);
char * p4 = my_malloc(1024);
return 0;
}


是不是有问题,在于管理这些内存的数据结构,上面的

const int MAX_BLOCKS = 256;
const int TOTAL_SIZE = 65536;
char buf[TOTAL_SIZE];
int ptr_alloced[MAX_BLOCKS];
int b_used[MAX_BLOCKS];
int cur_top = 0;
int currBlocks = 0;

是不是同一份。
baidu_28726667 2018-08-21
  • 打赏
  • 举报
回复
引用 6 楼 goldenhawking 的回复:
谁分配、谁释放。动态库:如果内部的 malloc 和外部的 free是配对的(共享一个内存管理结构),则不出错。静态:一定不行。


意思是如果malloc 和 free 的方法都放在静态库里也不行? 这是什么原因? 是windows还是 linux也会?!
  • 打赏
  • 举报
回复
谁分配、谁释放。动态库:如果内部的 malloc 和外部的 free是配对的(共享一个内存管理结构),则不出错。静态:一定不行。
赵4老师 2018-08-16
  • 打赏
  • 举报
回复
schlafenhamster 2018-08-16
  • 打赏
  • 举报
回复
通常是 谁分配,谁释放,
schlafenhamster 2018-08-16
  • 打赏
  • 举报
回复
"Because a DLL built by linking to a static CRT will have its own CRT state, it is not recommended to link statically to the CRT in a DLL unless the consequences of this are specifically desired and understood."

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧