473,473 Members | 1,482 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

basic allocating memory question

hi,
i'm reading a c++ book and noticed that the author seems to allocate
memory differently when using classes, he writes:

(assuming a class called CBox exists, with member function size()):
// first way
CBox x;
x.size();

// second way
CBox x = new CBox();
x.size();

// third way
CBox* x = new CBox();
x->size();

if i wrote sometime incorrectly, i apologize, i don't have the book in
front of me, my question was is there a difference among them, or is
it just a matter of preference? also can i allocate memory
dynamically for a char[] without using a pointer, or only when using a
pointer, like:

char* ptr = new char[some_variable];

where some_variable is just user input taken in during program
execution.

Thank you.
Jul 19 '05 #1
6 4105

"soni29" <so****@hotmail.com> wrote in message news:ca**************************@posting.google.c om...
(assuming a class called CBox exists, with member function size()):
// first way
CBox x;
x.size();
This is proper.

// second way
CBox x = new CBox();
x.size();
This won't even compile. C++ ain't JAVA. You don't have to "new"
non-dynamically allocated.
// third way
CBox* x = new CBox();
x->size();
This is valid. This allocates a dynamic CBox (you don't need the parens by the
way, but they don't hurt in this case). Note that since you new'd the object, you
must later delete it. x isn't a CBox in this case, but a pointer to the dynamically
allocated one. Generally, unless you need to do this, don't, use the first type
of allocation.
if i wrote sometime incorrectly, i apologize, i don't have the book in
front of me, my question was is there a difference among them, or is
it just a matter of preference? also can i allocate memory
dynamically for a char[] without using a pointer, or only when using a
pointer, like:

char* ptr = new char[some_variable];


Only when using a pointer.

Generally, at this poin't in your experience, you shouldn't be using either
C++'s broken array type or dynamic allocation. If you want a string,
use the string type. If you want an array of char for some reason, use
vector<char> my_array(some_variable).

Jul 19 '05 #2
"soni29" <so****@hotmail.com> wrote...
i'm reading a c++ book and noticed that the author seems to allocate
memory differently when using classes, he writes:

(assuming a class called CBox exists, with member function size()):
// first way
CBox x;
x.size();

// second way
CBox x = new CBox();
x.size();
This is an unlikely scenario. Looks too much like Java syntax (although
it is possible to emulate using C++ constructs as well).
// third way
CBox* x = new CBox();
x->size();

if i wrote sometime incorrectly, i apologize, i don't have the book in
front of me, my question was is there a difference among them, or is
it just a matter of preference?
Yes, there is a difference. If you write

CBox x;

in a function somewhere, the 'x' designates an "automatic" CBox which
lives only until the end of the block (compound statement) in which
it's defined.

If you write

CBox *x = new CBox();

'x' is a pointer to a "dynamic" CBox which lives until you dispose of
it by using "delete" operator (thus defying block boundaries).
also can i allocate memory
dynamically for a char[] without using a pointer, or only when using a
pointer, like:

char* ptr = new char[some_variable];

where some_variable is just user input taken in during program
execution.


Yes, you should be able to. 'some_variable' must be convertible to
'size_t' type. If it's an int or an unsigned, for example, then it
should work. Do you get error messages? If so, post more code and
copy the compiler diagnostic.

Victor
Jul 19 '05 #3

"soni29" <so****@hotmail.com> wrote in message
news:ca**************************@posting.google.c om...
hi,
i'm reading a c++ book and noticed that the author seems to allocate
memory differently when using classes, he writes:
There is no reason for allocating memory different when using classes. C++
has exactly the same memory allocating mechanisms for classes and
non-classes.

(assuming a class called CBox exists, with member function size()):
// first way
CBox x;
x.size();

// second way
CBox x = new CBox();
x.size();
Second way is not legal.

// third way
CBox* x = new CBox();
x->size();

if i wrote sometime incorrectly, i apologize, i don't have the book in
front of me, my question was is there a difference among them, or is
it just a matter of preference?
Plenty of difference. Ask yourself when the CBox object ceases to exist.

{
CBox x;
x.size();
} // CBox object ceases to exist here

{
CBox* x = new CBox;
x->size();
} // CBox object still exists

In the second example don't confuse the pointer x, with the CBox object it
is pointing to. The pointer x ceases to exist, but the object it is pointing
to lives on. The CBox object is no longer accessible (in this example)
because nothing is pointing at it, this is called a memory leak. Objects
allocated with new are only destroyed when you call delete on them, and that
can happen at any time you like. Objects 'allocated' like the first example
are always destroyed when the program exits the 'scope' in which they were
declared.
also can i allocate memory
dynamically for a char[] without using a pointer, or only when using a
pointer, like:

char* ptr = new char[some_variable];

where some_variable is just user input taken in during program
execution.

Thank you.


All dynamic memory allocation involves pointers.

Some compilers do let you do this

int some_variable;
....
char array[some_variable];

but that is not legal C++ and those compilers should be ashamed of
themselves.

john
Jul 19 '05 #4

"soni29" <so****@hotmail.com> wrote in message
news:ca**************************@posting.google.c om...
hi,
i'm reading a c++ book and noticed that the author seems to allocate
memory differently when using classes, he writes:

(assuming a class called CBox exists, with member function size()):
// first way
CBox x;
x.size();

// second way
CBox x = new CBox();
x.size();

// third way
CBox* x = new CBox();
x->size();
That is only the second way (the function size has nothing to do with
allocating storage.
if i wrote sometime incorrectly, i apologize, i don't have the book in
front of me, my question was is there a difference among them, or is
it just a matter of preference? also can i allocate memory
dynamically for a char[] without using a pointer, or only when using a
pointer, like:

char* ptr = new char[some_variable];


That is still the second way (new). You use the second way when you don't
know when you write the program if you'll need that memory or not. Read up
on "dynamic memory allocation" for more info.
Jul 19 '05 #5
Thank you all for the responses, again sorry about the CBox x = new
CBox(); i'm more use to Java than C++ and thought i saw that, guess i
was wrong. but i'm still a little confused about the other two
methods:
CBox x;
x.size();

CBox* x = new CBox();
x->size();

is there a preference, one person mentioned to use the first,
but Mr. Bazarov wrote:
"'x' is a pointer to a "dynamic" CBox which lives until you dispose of
it by using "delete" operator (thus defying block boundaries)."

while Mr. Harrison wrote:
"The pointer x ceases to exist, but the object it is pointing
to lives on. The CBox object is no longer accessible (in this example)
because nothing is pointing at it, this is called a memory leak."

so is the x alive after the scope? if it's alive than i can see the
difference, i could then use x outside of the scope to get a my CBox
object, if not then they seem similar, aside from the extra step
required in deleting the x pointer from the heap. if it ceases to
exist then why bother with all the pointer notation and rememebering
to delete it, why not just stick to the first method? sorry about the
simply questions, just trying to figure out what is the most common
way, if there is a suggested standard, or just whatever you like since
they both get you to the object, just that with one you need to delete
it yourself.

Thank you.
Jul 19 '05 #6
soni29 wrote:
<confusion about dynamic versus automatic variables>

The best way I can think of to explain it is with an example.

void f()
{
int *p1 = new int; /* dynamic int comes into existence */
int *p2 = new int; /* dynamic int comes into existence */

int a; /* a comes into existence here */

// ...

if (true)
{
int b; /* b comes into existence here */

// ...

} /* b ceases to exist here */

delete p1; /* the thing p1 points to ceases to exist here */

// ...

} /* a ceases to exist here */

/* after the function completes, the thing
p2 points to still exists */
Things created without 'new' cease to exist at the end of the block they
are declared in (unless they are declared 'static'). If they aren't
declared in a block, they exist to the end of the program.

Things created with 'new' continue to exist until you delete them. If
you fail to delete them, you get a memory leak (or worse). They are not
confined to the function they are created in, they exist until you tell
them to stop existing via 'delete'.

'new' is somewhat dangerous because there's a chance you'll forget to
'delete' the thing when you are done, and 'new' may throw an exception
if there's not enough memory to complete the request. Therefore it
should usually only be used when you require explicit control over the
lifetime of an object.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: solartimba | last post by:
I am a stats man that uses C++ to analyze stock data, but I have run into a problem regarding memory usage. First, though, I need to give a little background info. I want to write a program...
4
by: Sameer | last post by:
Hello Group, This is one problem in programming that is troubling me. there is a segmentation fault just before creating memory to a structure ..i.e, just after the "allocating memory "...
3
by: Erik S. Bartul | last post by:
lets say i want to fill up a multidimentional array, but i wish to allocate memory for it on the fly. i assume i declare, char **a; but how do i allocate memory for the pointers, so i can...
18
by: steve | last post by:
I'm trying to create a structure of three pointers to doubles. For which I have: typedef struct { double *lst_t, *lst_vc, *lst_ic; } last_values; I then need to allocate space for...
3
by: Tod Birdsall | last post by:
Hi All, The organization I am working for has created a new corporate website that used Microsoft's Pet Shop website as their coding model, and dynamically served up content, but cached each...
3
by: Sally Sally | last post by:
I have a very basic question on the two parameters shared buffers and effective cache size. I have read articles on what each is about etc. But I still think I don't quite grasp what these settings...
8
by: kathy | last post by:
If I have 2D array like: int **p; p = new int*; for(int i=0;i<10;i++) { p = new int; }
29
by: K. Jennings | last post by:
I would like to get the result of malloc() such that it is aligned on a given boundary - 8, in this case. Assuming that sizeof(u64) is 8, will u64 *p = malloc(N) ; do the trick in general? ...
13
by: Aarti | last post by:
I have a very elementary question about pointers. Please pardon me for my ignorance of C int main() { int* i; *i = 1 //at times this may give me a core dump. const char* str = "test"; //This...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.