c - 无法使用 sizeof() 检查内存分配大小

标签 c visual-studio-2010 malloc

<分区>

我正在尝试检查通过 malloc() 分配的指针内存的大小。为此,我编写了一个程序,其中我最初分配的内存大小为 10。然后插入一个 for 循环并使用 realloc() 不断增加内存。我正在使用 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”作为输出:

enter image description here

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

最佳答案

ptrchar * 类型,所以 sizeof(*ptr) 等价于 sizeof(char),这就是为什么您总是在输出中得到 1

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

关于c - 无法使用 sizeof() 检查内存分配大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28911789/

相关文章:

c - 字数统计程序 - stdin

字符计数程序不输出任何东西?

CUDA 2D 数组赋值

c - 信号 SIGTRAP 免费崩溃

C 编程,使用 BUFSIZ、malloc 和 memset 的缺陷

c - 简单 MPI 发送/接收程序中的行为不明确

visual-studio-2010 - Visual Studio以 'Release'模式运行项目,但不以 'Debug'模式运行

visual-studio-2010 - 如何在不重新启动 Windows Azure 模拟器的情况下编辑和查看更改?

visual-studio-2010 - Visual Studio 代码生成——如何处理开发人员编辑类文件

linux - 如何分配 4k 对齐的内存