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.
请帮我写一个函数来查找动态分配的内存。
2 个解决方案
#1
3
The short and only answer is that you can't. You simply have to keep track of it yourself.
简短而唯一的答案是你做不到。你只需要自己跟踪它。
#2
2
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.
没有办法以编程方式知道在调用malloc()时分配了多少字节。您需要单独跟踪该大小,并在需要的地方传递该大小。
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);
}
#1
3
The short and only answer is that you can't. You simply have to keep track of it yourself.
简短而唯一的答案是你做不到。你只需要自己跟踪它。
#2
2
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.
没有办法以编程方式知道在调用malloc()时分配了多少字节。您需要单独跟踪该大小,并在需要的地方传递该大小。
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);
}