Re: Getting memory size
On 1 Mai, 21:11, Nimish <nimish.bharg...@gmail.com> wrote:
How can I find the size of memory allocated to the pointer.
For eg.
int main()
{
int b[100];
int *a = b;
....
return 0;
}
In this function I want to get size of memory allocated to "a"
pointer.
How can this be done.
There does not exist a general solution and you
need to administrate such information on your
own. Try to view from the point of an implementator
of a language like C++ supports several different
kinds of storage duration. Compare the following
assignments:
void foo(int* p) {
// How to get size of object pointed by p?
}
void bar() {
int i = 12;
foo(&i); //#1
int b[100];
foo(b); //#2
int* d = new int[12];
foo(d); //#3
delete[] d;//3b
}
In cases #1 and #2 the compiler has no need to
persist the information of i or b (except the object
address) somewhere so that we cannot expect to use
a generally valid mechanism in foo to access it.
We can view #3 as a border case. It's rather probable,
that a compiler has some means to get the information
about the memory size, that has been reserved
for d, otherwise it wouldn't be capable to release
this again in #3b. But this number is not necessarily
identical to the size that we as programmers would
expect (e.g. the standard does not guarantee that this
size will be exactly 12*sizeof(int)), so there does
not exist a publicly available accessor to this
information.
There are different means to realize what you want.
E.g. if you restrict on C arrays which are provided
without pointer conversion to the actual function,
you can use a template, e.g.
template<typename T, size_t N>
void foo2(T (&)[N]) {
std::cout << "Size is " << N;
}
void bar() {
int b[100];
foo2(b); // OK, N = 100
}
This template-based approach can be used to
create a tool like this one from boost:
template< typename T, size_t N>
char (&sizer(const T (&)[N]))[N];
template< typename T, size_t N>
char (&sizer(T (&)[N]))[N];
void bar() {
int b[100];
size_t size_of_b = sizeof(sizer(b)); // OK, returns 100
}
Alternatively you could instead use an
intelligent arrays wrapper like boost::array
(which is going to become std::array):
void bar() {
boost::array<int, 100> b;
size_t size_of_b = b.size(); // OK, 100 returned
}
If you are working with dynamically allocated
storage, you have to track this information of
your own or better use an existing wrapper class,
which does the same for you, e.g.
void bar() {
std::vector<int> b(100);
size_t size_of_b = b.size(); // OK, 100 returned
}
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]