basic allocating memory question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • soni29

    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.
  • Ron Natalie

    #2
    Re: basic allocating memory question


    "soni29" <soni29@hotmail .com> wrote in message news:cad7a075.0 309041002.19dda 9fb@posting.goo gle.com...
    [color=blue]
    > (assuming a class called CBox exists, with member function size()):
    > // first way
    > CBox x;
    > x.size();[/color]

    This is proper.
    [color=blue]
    >
    > // second way
    > CBox x = new CBox();
    > x.size();[/color]

    This won't even compile. C++ ain't JAVA. You don't have to "new"
    non-dynamically allocated.[color=blue]
    >
    > // third way
    > CBox* x = new CBox();
    > x->size();[/color]

    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.
    [color=blue]
    > 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];[/color]

    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_v ariable).



    Comment

    • Victor Bazarov

      #3
      Re: basic allocating memory question

      "soni29" <soni29@hotmail .com> wrote...[color=blue]
      > 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();[/color]

      This is an unlikely scenario. Looks too much like Java syntax (although
      it is possible to emulate using C++ constructs as well).
      [color=blue]
      > // 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?[/color]

      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).
      [color=blue]
      > 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.[/color]

      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


      Comment

      • John Harrison

        #4
        Re: basic allocating memory question


        "soni29" <soni29@hotmail .com> wrote in message
        news:cad7a075.0 309041002.19dda 9fb@posting.goo gle.com...[color=blue]
        > hi,
        > i'm reading a c++ book and noticed that the author seems to allocate
        > memory differently when using classes, he writes:[/color]

        There is no reason for allocating memory different when using classes. C++
        has exactly the same memory allocating mechanisms for classes and
        non-classes.
        [color=blue]
        >
        > (assuming a class called CBox exists, with member function size()):
        > // first way
        > CBox x;
        > x.size();
        >
        > // second way
        > CBox x = new CBox();
        > x.size();[/color]

        Second way is not legal.
        [color=blue]
        >
        > // 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?[/color]

        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.
        [color=blue]
        > 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.[/color]

        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


        Comment

        • jeffc

          #5
          Re: basic allocating memory question


          "soni29" <soni29@hotmail .com> wrote in message
          news:cad7a075.0 309041002.19dda 9fb@posting.goo gle.com...[color=blue]
          > 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();[/color]

          That is only the second way (the function size has nothing to do with
          allocating storage.
          [color=blue]
          > 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];[/color]

          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.


          Comment

          • soni29

            #6
            Re: basic allocating memory question

            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.

            Comment

            • Kevin Goodsell

              #7
              Re: basic allocating memory question

              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.

              Comment

              Working...