In one function I have written:
char *ab;
ab=malloc(10);
Then in another function I want to know the size of memory pointed b开发者_如何学JAVAy the ab
pointer.
Is there any way that I can know that ab
is pointing to 10 chars of memory?
No, you don't have a standard way to do this. You have to pass the size of the pointed-to memory along with the pointer, it's a common solution.
I.e. instead of
void f(char* x)
{
//...
}
use
void f(char *x, size_t length)
{
//....
}
and in your code
char *ab = malloc( 10 );
f( ab, 10 );
It's a deep secret that only free() knows for sure. It's likely in your system, but in a totally implementation dependent manner.
A bit awkward, but if you want to keep everything together:
typedef struct { // size of data followed by data (C only trick! NOT for C++) int dimension; // number of data elements int data[1]; // variable number of data elements } malloc_int_t; malloc_int_t *ab; int dimension = 10; ab = malloc( sizeof(*ab) + (dimension-1)*sizeof(int) ); ab->dimension = dimension; ab->data[n] // data access
I've changed the data type to int to make the code a more generic template.
You can't (portably anyway). You have to keep track of the size yourself.
Some implementations of malloc
could give you an API to access that information, but there is no provisions in the standard for this.
The size is what you passed into malloc
, you can use a global variable or macro to remember it.
There is no way, you have to store the size of the allocated memory in another variable.
No, unfortunately.
You need to pass the size of the block along with the pointer.
No.
Now, that being said, there are non-portable hacks to do this, but it is not safe to rely upon them.
If you know with 100% certainty that the memory was allocated via malloc(), you may be able to rewind the pointer a few bytes and inspect the 'malloc node' that is used to track which parts of memory have been allocated and which have not. However, I can not stress this enough--do not ever depend upon this.
There is no way to deduce the size of allocated memory from the pointer itself. Since ab
is a char *
, sizeof(ab)
is the same as sizeof(char *)
, which obviously is not the same as the size of the allocated chunk of memory.
Since you called malloc
with the required size, you know what the size is. Pass this number along with the pointer to the function that needs to know the size.
I had a structure and a char pointer pointing to its memory address. So relating it to your question, I wanted to find the size of the memory location it was pointing to i.e. the size of the structure. So logically what you do is, find the size of the object the pointer creates to. This worked for me:
unsigned char * buffer= Library1Structure;
int x=sizeof(Library1Structure);
So the value of x tells me the size of the memory location the pointer buffer points to.
精彩评论