By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,084 Members | 1,969 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,084 IT Pros & Developers. It's quick & easy.

Variable Memory Usage

P: n/a
Is there a way in C++ to show how much memory a variable is using?

Take this for example:

char *testVar = new char[512];

Is there a way to find out that I can put 512 characters in this
before we go out of bounds?

Thanks in advanced!

Aug 14 '07 #1
Share this Question
Share on Google+
5 Replies


P: n/a
Chad wrote:
Is there a way in C++ to show how much memory a variable is using?

Take this for example:

char *testVar = new char[512];

Is there a way to find out that I can put 512 characters in this
before we go out of bounds?
No, there isn't a standard way.

--
Ian Collins.
Aug 14 '07 #2

P: n/a
Chad wrote:
Is there a way in C++ to show how much memory a variable is using?
It depends on kind of variable.

--
j..
<adres<- ROT13 <adres>
--------------------
Aug 14 '07 #3

P: n/a
"Chad" <ch**@mizmoz.comwrote in message
news:11**********************@l70g2000hse.googlegr oups.com...
Is there a way in C++ to show how much memory a variable is using?
Yes. sizeof
Take this for example:

char *testVar = new char[512];
testVar takes sizeof(testVar) bytes of memory (on my system 4).
Is there a way to find out that I can put 512 characters in this
before we go out of bounds?
Not cross platform and not even always platform specific. You don't want to
know how much memory a variable us using, but how much memory is allocated
to a pointer. No way to know in standard C++.
Aug 14 '07 #4

P: n/a
Hi!

Jim Langston schrieb:
"Chad" <ch**@mizmoz.comwrote in message
news:11**********************@l70g2000hse.googlegr oups.com...
>char *testVar = new char[512];

testVar takes sizeof(testVar) bytes of memory (on my system 4).
sizeof does not return the size in bytes, AFAIK. It returns units of
sizeof(char) which is defined as "1". A "char" has "CHAR_BITS" bits
which may be more than 8.

In general it is not defined that a byte always has 8 bits. That's why
the term "octet" was inventet.

Frank
Aug 14 '07 #5

P: n/a
Hi!

Chad schrieb:
Take this for example:

char *testVar = new char[512];

Is there a way to find out that I can put 512 characters in this
before we go out of bounds?
The other replies already told you. But you got no alternative. Here is one:

#include <vector>

std::vector<chartestVar(512);
testVar.size(); //returns 512
char* beginning = &testVar[0];

Maybe take a look here: http://www.cppreference.com/cppvector/index.html

HTH,
Frank
Aug 14 '07 #6

This discussion thread is closed

Replies have been disabled for this discussion.