C - 来自void *的sizeof值,之前是malloced?

时间:2017-02-24 08:38:08

标签: c pointers memory

我正在创建一个文件,其工作专门用于跟踪我当前分配的块数,因为我不想要任何内存泄漏。

size_t BLOCKS_CURRENTLY_ALLOCATED = 0;

/* Since variables can be allocated in lots of different ways,
malloc, calloc, realloc, etc don't allocate here. Just mark down
how many bytes of memory was used for this value. */
void allocate(const void const *val)
{
    BLOCKS_CURRENTLY_ALLOCATED += sizeof(*val);
}

/* Update the amount of blocks counter and free the pointer. */
void deallocate(const void const *val)
{
    // Edit: I think I meant to do `sizeof(val)` but I don't know if that works
    const size_t size = sizeof(*val);
    if (BLOCKS_CURRENTLY_ALLOCATED < size)
        exit(1); // Error, must have forgotten to report allocating.
    free(val);
    BLOCKS_CURRENTLY_ALLOCATED -= sizeof(size);
}

此代码是否合法?我是否能够使用sizeof来获取为某个未分配的数据类型指针分配的块数量,该指针在某个时间点分配有malloccalloc?如何在数据为free且指针为const的指针上调用const

1 个答案:

答案 0 :(得分:-2)

这是一个错误!

void* a; sizeof(a);如果是vaild,因为每个指针的大小是4个字节。

void* a; sizeof(*a);不是虚荣的,因为你永远不知道指向的void指针是什么,所以你永远不知道它的大小是多少。它可以是char,int,指针......

另外,如果你写void* ?=malloc(??)这个命令(sizeof(?))将返回4.不是??。