无法使用 sizeof() 检查内存分配大小 [英] Unable to check memory allocation size with sizeof()

查看:76
本文介绍了无法使用 sizeof() 检查内存分配大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查通过 malloc()分配的指针内存的大小.为此,我编写了一个程序,最初分配的内存大小为10.然后插入一个for循环,并使用 realloc()保持增加的内存.我正在使用 sizeof 检查内存大小.

I am trying to check the size of pointer memory allocated through malloc(). For this I write a program in which I initially allocate memory size of 10. Then insert a for loop and keep increasing memory by using realloc(). I am checking memory size by using sizeof.

这是我的代码:

int main(int argc, _TCHAR* argv[])
{
    char *ptr;
    long int size;
    int count;

    ptr = (char *) malloc(10);
    size = sizeof(*ptr);
    printf("size of ptr is= %d\n",size);

    for(count=11;count<=100;count++)
    {
        ptr=(char *) realloc(ptr,count);
        size = sizeof(*ptr);
        printf("size of ptr is= %d\n",size);
    }

    return 0;
}

但我的输出始终为'1':

But I am getting always '1' as output:

所以,请告诉我是否还有其他方法可以做到这一点.

So, please tell me if there is any other way to do this.

推荐答案

ptr 的类型为 char * ,因此 sizeof(* ptr)等同于 sizeof(char),这就是为什么您总是在输出中得到 1 的原因.

ptr is of type char *, so sizeof(*ptr) is equivalent to sizeof(char), that's why you always get 1 in the output.

一般来说,没有可移植的方法从 malloc 返回的指针中获取内存大小,您需要手动记住大小.

In general, there's no portable way to get the memory size from the pointer that malloc returns, you need to remember the size manually.

这篇关于无法使用 sizeof() 检查内存分配大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆