Getting the size of a malloc only with the returned pointer

折月煮酒 提交于 2019-11-27 09:20:55

The pointer is a pointer, and not an array. It can never be "recognized as an array", because it is not an array.

It is entirely up to you to remember the size of the array.

For example:

struct i_must_remember_the_size
{
    size_t len;
    int * arr;
};

struct i_must_remember_the_size a = { 10, NULL };
a.arr = malloc(a.len * sizeof *a.arr);

There's no standard way to do what you ask. Some compilers may provide a function for that, or some other allocators may have such a function, but, as already said there's nothing standard.

Notice that the sizeof applied over arrays does not work because it recognizes the pointer "as from an array": it just recognizes its argument as an array (sizeof is one of the few contexts in which an array do not decay to a pointer to its first element); once your array decays to a pointer sizeof will only yield the size of the pointer.

First of all, sizeof() returns the size of a "type"; it doesn't know a thing about allocated memory.

Second, there is no way to get the size of a malloc()ed block, UNLESS you want to dig into the internals of the runtime library of your compiler. Which is most definitely not a good idea, especially since it's no problem to remember the size elsewhere --- you could prefix the memory block with another item to store the size, or you could store it separately.

In C standard and portable, it's impossible. Just notice that some compilers provide nonstandard extensions (keep track of it, e.g. msize).

Besides, the sizeof operator can't tell you the size of the block, so it yields the size of the pointer (remember that sizeof operates at compile time, except with variable length arrays).

So you have to keep the size alloced, e.g. in a data structure such as :

#include <stddef.h>

typedef struct {
    int   *p;
    size_t n;
} array;

Use a pointer-to-array type rather than a pointer-to-element type:

int (*parray)[10] = malloc(sizeof *parray);

Then sizeof *parray gives you the desired answer, but you need to access the array using the * operator, as in (*parray)[i] (or equivalently albeit confusingly, parray[0][i]). Note that in modern C, 10 can be replaced with a variable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!