简体   繁体   中英

How to find Dynamically allocated size in c language?

Write a function to find exact size of dynamically created * variable ?

Guys it is working but for static allocation only...

int alp=0;
printf("%d",(char*)(&alp+1)-(char*)(&alp));

it will return 4 correct size, which is size of int at 32 bit machine but not working with dynamically allocated pointer variable.

char *c=(char *)malloc(12*sizeof(char));

How to find size of *c which is actually 12 here ??

please Help me to write a function to find dynamically allocated memory.

The short and only answer is that you can't. You simply have to keep track of it yourself.

There's no way to know programmatically how many bytes were allocated in a call to malloc() . You need to keep track of that size separately and pass that size around where needed.

For example:

void myfunc(char *c, int size)
{
    int i;
    for (i=0;i<size;i++) {
        printf("c[%d]=%c\n",size,c[size]);
    }
}

int main()
{
    int len=10;
    char *c = malloc(len);
    strcpy(c,"hello");
    myfunc(c,len);
    free(c);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM