简体   繁体   English

如何在C语言中找到动态分配的大小?

[英]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. 它将返回4个正确的大小,这是32位计算机上int的大小,但不适用于动态分配的指针变量。

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

How to find size of *c which is actually 12 here ?? 如何找到* c的大小,实际上这里是12

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() . 无法以编程方式知道在对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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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