Alex Rivera | Logout

how can i know the allocated memory size of pointer variable in c

Asked 2011-08-26T08:38:34.700
9

I have faced some problem in this case can you please your ideas.

main()
{
char *p=NULL;
p=(char *)malloc(2000 * sizeof(char));
printf("size of p = %d\n",sizeof (p));
}

In this program Its print the 4 that (char *) value,but i need how many bytes allocated for that.

Edit
Report

1 Answer

3

Although it may be possible that some libraries allows you to determine the size of an allocated buffer, it wouldn't be a standard C function and you should be looking at your library's own documentations for this.

However, if there are many places that you need to know the size of your allocated memory, the cleanest way you could do it is to keep the size next to the pointer. That is:

struct pointer
{
    size_t size;
    void *p;
};

Then every time you malloc the pointer, you write down the size in the size field also. The problem with this method however is that you have to cast the pointer every time you use it. If you were in C++, I would have suggested using template classes. However, in this case also it's not hard, just create as many structs as the types you have. So for example

struct charPtr
{
    size_t size;
    char *p;
};
struct intPtr
{
    size_t size;
    int *p;
};
struct objectPtr
{
    size_t size;
    struct object *p;
};

Given similar names, once you define the pointer, you don't need extra effort (such as casting) to access the array. An example of usage is:

struct intPtr array;
array.p = malloc(1000 * sizeof *array.p);
array.size = array.p?1000:0;
...
for (i = 0; i < array.size; ++i)
    printf("%s%d", i?" ":"", array.p[i]);
printf("\n");
answered 2011-08-26T08:59:45.687

Your Answer