如何获得一个指针的大小

高性能架构探索 2011-03-11 12:03:32

如下代码
int *pI = new int;
int *pII = (int *)malloc(sizeof(int));

怎么样知道pI和pII所指向的内存块的大小...
...全文
176 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
we_sky2008 2011-03-11
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 we_sky2008 的回复:]
引用 2 楼 we_sky2008 的回复:
楼主可以试下_msize这个函数,

C/C++ code

#include <iostream>
#include <malloc.h>

using namespace std;

void test()
{
int *pI = new int;
int *pII = (int *)malloc(sizeof(int))……
[/Quote]
再更正:

#include <iostream>
#include <malloc.h>

using namespace std;

void test()
{
int *pI = new int[10];
int *pII = (int *)malloc(sizeof(int) * 100);

cout<<(_msize(pI))<<endl;
cout<<(_msize(pII))<<endl;

delete[] pI;
free(pII);
}

int main()
{
test();

system("pause");
return 0;
}

  • 打赏
  • 举报
回复
谢谢we_sky2008
ouyh12345 2011-03-11
  • 打赏
  • 举报
回复
有这种需要的话,重载new,或者用另一个函数来分配内存
we_sky2008 2011-03-11
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 we_sky2008 的回复:]
楼主可以试下_msize这个函数,

C/C++ code

#include <iostream>
#include <malloc.h>

using namespace std;

void test()
{
int *pI = new int;
int *pII = (int *)malloc(sizeof(int));

cout……
[/Quote]
更正:

#include <iostream>

using namespace std;

void test()
{
int *pI = new int;
int *pII = (int *)malloc(sizeof(int));

cout<<(_msize(pI))<<endl;
cout<<(_msize(pII))<<endl;

delete pI;
free(pII);
}

int main()
{
test();

system("pause");
return 0;
}
  • 打赏
  • 举报
回复
比如Free(pfree),
因为我实现的函数功能如下:如果申请的字节数小于某一个值,那么我就我自己的内存管理,否则用malloc来申请
但是现在遇到的问题是 在Free里面,我怎样知道该用系统free释放还是用我自己定义的函数来释放

如果用参数的话,比如Free(pfree, size);这样的话,我就不能用统一的函数接口

比如
#define FREE(pfree) Free(pfree)
we_sky2008 2011-03-11
  • 打赏
  • 举报
回复
楼主可以试下_msize这个函数,

#include <iostream>
#include <malloc.h>

using namespace std;

void test()
{
int *pI = new int;
int *pII = (int *)malloc(sizeof(int));

cout<<(_msize(pI))<<endl;
cout<<(_msize(pII))<<endl;

delete pI;
delete[]pII;
}

int main()
{
test();

system("pause");
return 0;
}
pengzhixi 2011-03-11
  • 打赏
  • 举报
回复
额 你应该需要用个变量保存这个大小。

64,643

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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