在仿写stl的过程中,被一处内存错误卡了很久。当内存池需要多次malloc时会出现堆损坏的错误,初步判断是数组越界,但总是检查不出来。一开始用Dr.Memory检查不出来,就试了一下devpartner。官网链接 http://www.borland.com/zh-CN/Products/Software-Testing/Automated-Testing/Devpartner-Studio
devpartner安装完后会自动在vs上装插件,但是那个插件好像没什么用。我是直接在安装目录下找到blockchecker,并用它打开要调试的exe,再点击运行,就能看到检测到的错误,如图
它提示这里指针运算范围错误,那为什么会错误呢?可以看到上面的代码
*my_free_list = next = (obj *)chunk + n;
应为
*my_free_list = next = (obj *)(chunk + n);
原来是忘了加括号了!!因为obj型指针和char型指针大小是不一样的,所以和n相加结果自然也不一样。一个括号浪费了我这么多时间。。。所以有个好的工具是多么重要。但是再好的工具也不能明确地指出是哪里出错,就像上面的例子,最后一步还是要我们自己推出来。
1 //返回一个大小为n的对象,并可能加入大小为n的其他区块到freelist
2 //在ANSI c中,void *不允许进行加减操作,所以chunk用char *
3 void *default_alloc::refill(size_t n)
4 {
5 int objs = 20;
6 char *chunk = chunk_alloc(n, objs);
7
8 obj *next = nullptr, *current = nullptr;
9 obj *result = nullptr;
10 obj **my_free_list = nullptr;
11 if (1 == objs) //只取出一个区块
12 return chunk;
13 my_free_list = free_list + FREELIST_INDEX(n);
14 result = (obj *)chunk; //这一块返回给客户端
15 //将freellist指向分配的区域
16 *my_free_list = next = (obj *)(chunk + n);
17 for (int i = 1;; i++)
18 {
19 current = next;
20 next = (obj *)((char *)next + n); //这里注意不能直接用next+n
21 if (i == objs - 1)
22 {
23 current->next = nullptr;
24 break;
25 }
26 else
27 current->next = next;
28 }
29 return result;
30 }
View Code
原文链接: https://www.cnblogs.com/tonychen-tobeTopCoder/p/5193865.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/228786
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!