Another dynamic memory doubt

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

    #1

    Another dynamic memory doubt

    Hello friends:

    I have the following code,

    char* MyClass::MyMeth od()
    {
    char* ptr = new char[6]; // space for NULL terminator
    ptr = "hello";
    return ptr;
    delete[] ptr;
    }

    What I'm trying to do is return ptr, but delete[] it afterwards. In the
    code above, I believe the delete[] line will not be executed following
    the return statement.

    How should I achieve this?

    Thanks.
  • Antoninus Twink

    #2
    Re: Another dynamic memory doubt

    On 26 Apr 2008 at 9:46, pradeep wrote:
    I have the following code,
    There are several problems and misunderstandin gs in your code...
    char* MyClass::MyMeth od()
    In C++, it's usually better to #include <stringand then use
    std::string instead of C-style strings. You can always get a good old
    char * back if necessary by using the c_str() method.
    {
    char* ptr = new char[6]; // space for NULL terminator
    ptr = "hello";
    This does not copy the string "hello" into the array you've just
    allocated, but rather makes ptr point to the start of a string literal,
    which will be stored in the data segment of your object file.

    A consequence of this is that you have leaked the memory you allocated
    on the line before, and trying to delete ptr will cause problems.
    return ptr;
    delete[] ptr;
    }
    >
    What I'm trying to do is return ptr, but delete[] it afterwards. In the
    code above, I believe the delete[] line will not be executed following
    the return statement.
    Of course not! A return statement moves you up a stack frame, and in
    particular sets the program counter to where it was when you called the
    function.
    How should I achieve this?
    In the documentation for your function, explain that it allocates some
    memory and that the caller is responsible for deleting ptr.

    Or don't allocate memory at all, but just have

    char* MyClass::MyMeth od()
    {
    return "hello";
    }

    Comment

    • santosh

      #3
      Re: Another dynamic memory doubt

      pradeep wrote:
      Hello friends:
      >
      I have the following code,
      >
      char* MyClass::MyMeth od()
      This is C++. There is a dedicated group for C++ called comp.lang.c++.
      Try that.

      <snip>

      Comment

      • Martin Ambuhl

        #4
        Re: Another dynamic memory doubt

        pradeep wrote:
        Hello friends:
        >
        I have the following code,
        >
        char* MyClass::MyMeth od()
        ^^^^^^^^ This line is a syntax error in C.
        {
        char* ptr = new char[6]; // space for NULL terminator
        ^^^^^^^^ This line is a syntax error in C.
        ptr = "hello";
        ^^^^^^^^ If the preceding non-C line allocated space for a char[6] and
        assigned the address of the first element to ptr, then
        this line creates a memory leak and loses the address of
        the char[6] array.
        return ptr;
        delete[] ptr;
        ^^^^^^^^ This line is a syntax error in C, and even if it weren't,
        the return in the line before makes this line unreachable.
        }
        >
        What I'm trying to do is return ptr, but delete[] it afterwards.
        In the foolish language you are grossly misusing, you will need to
        delete the array separately. However, since you have assigned the
        addess of the anonymous char literal "hello" to ptr, that is almost
        guaranteed to blow up in your face. After you go back and read your
        textbook and read the FAQ for the newsgroup for the language you are
        using, ask in that newsgroup. It is very likely that the language you
        are misusing in C++, and its newsgroup is <news:comp.lang .c++>.

        In the
        code above, I believe the delete[] line will not be executed following
        the return statement.
        >
        How should I achieve this?
        By not coding randomly and praying that whatever you type is legal. Put
        some effort into actually learning the language.

        Comment

        • santosh

          #5
          Re: Another dynamic memory doubt

          Antoninus Twink wrote:
          On 26 Apr 2008 at 9:46, pradeep wrote:
          >I have the following code,
          >
          There are several problems and misunderstandin gs in your code...
          <snip C++ code and response>

          Nowhere in your post did you mention to the OP that there is in fact a
          dedicated Usenet group for C++ where answers are likely to be more
          correct than OT responses in other groups. Why is that? Do you
          deliberately want the OP to remain ignorant of the best forum for help
          with his problem and risk betting on possibly incorrect or outdated
          advice in other groups?

          Answering questions on non-conforming C code is one thing but answering
          questions on totally separate languages and other wildly OT matters
          (like the recent thread on Ethernet cables) seems a deliberate tactic
          to lower the S:N ratio and wreck this group.

          Comment

          • Walter Roberson

            #6
            Re: Another dynamic memory doubt

            In article <fuutl3$ecb$1@a ioe.org>, pradeep <nospam@nospam. comwrote:
            >I have the following code,
            >char* MyClass::MyMeth od()
            That line is a syntax error. The only place that a colon (':')
            can occur in a type description in C is as a bit-field length
            within a structure definition.
            >{
            char* ptr = new char[6]; // space for NULL terminator
            That line is a syntax error. There is no storage class named 'new'
            in C.
            ptr = "hello";
            return ptr;
            delete[] ptr;
            Another syntax error.
            >}
            >What I'm trying to do is return ptr, but delete[] it afterwards. In the
            >code above, I believe the delete[] line will not be executed following
            >the return statement.
            >How should I achieve this?
            How can you be assured that the pointer would not be deleted until
            after the calling routine had finished accessing the data??
            If you create storage and return a pointer to that storage, you cannot
            also delete that storage, not unless the calling routine will never
            attempt to access the storage nor to test the pointer against anything
            other than a null pointer constant.

            One would suspect that your code is not in fact C code, in
            which case our most charitable assumption would be that you
            have -accidently- posted your question to the wrong newsgroup.

            But even if so, you need to figure out what it is supposed to
            mean to delete a pointer to a storage area when you have returned
            that pointer outwards. There are not many languages around
            (-none- that I can think of right now) in which returning a pointer
            to a memory block is understood to mean that the procedure
            calling mechanism should take a -copy- of the storage pointed to
            and put that copy somewhere for future use.
            --
            "History is a pile of debris" -- Laurie Anderson

            Comment

            • Malcolm McLean

              #7
              Re: Another dynamic memory doubt


              "pradeep" <nospam@nospam. comwrote in message news:fuutl3$ecb $1@aioe.org...
              Hello friends:
              >
              I have the following code,
              >
              char* MyClass::MyMeth od()
              {
              char* ptr = new char[6]; // space for NULL terminator
              ptr = "hello";
              return ptr;
              delete[] ptr;
              }
              >
              What I'm trying to do is return ptr, but delete[] it afterwards. In the
              code above, I believe the delete[] line will not be executed following the
              return statement.
              >
              How should I achieve this?
              >
              You want C++, next door.
              However most programming languages have the feature that statements after a
              return are not executed. The answer is to put those statements in the
              calling code.

              --
              Free games and programming goodies.


              Comment

              • Ben Bacarisse

                #8
                Re: Another dynamic memory doubt

                Antoninus Twink <nospam@nospam. invalidwrites:
                On 26 Apr 2008 at 9:46, pradeep wrote:
                >I have the following code,
                >char* MyClass::MyMeth od()
                >
                In C++, ...
                I won't point out the C++ errors you made (that would be to fall into
                your trap) but the original poster should know:

                (a) that comp.lang.c++ is the place to ask;
                (b) answers here will not checked by people who really know C++;
                (c) your answer was not correct (IMO, but see (b)).

                --
                Ben.

                Comment

                • Richard

                  #9
                  Re: Another dynamic memory doubt

                  roberson@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
                  In article <fuutl3$ecb$1@a ioe.org>, pradeep <nospam@nospam. comwrote:
                  >
                  >>I have the following code,
                  >
                  >>char* MyClass::MyMeth od()
                  >
                  That line is a syntax error. The only place that a colon (':')
                  can occur in a type description in C is as a bit-field length
                  within a structure definition.
                  >
                  >>{
                  > char* ptr = new char[6]; // space for NULL terminator
                  >
                  That line is a syntax error. There is no storage class named 'new'
                  in C.
                  >
                  > ptr = "hello";
                  > return ptr;
                  > delete[] ptr;
                  >
                  Another syntax error.
                  >>}
                  >
                  >
                  >>What I'm trying to do is return ptr, but delete[] it afterwards. In the
                  >>code above, I believe the delete[] line will not be executed following
                  >>the return statement.
                  >
                  >>How should I achieve this?
                  >
                  How can you be assured that the pointer would not be deleted until
                  after the calling routine had finished accessing the data??
                  If you create storage and return a pointer to that storage, you cannot
                  also delete that storage, not unless the calling routine will never
                  attempt to access the storage nor to test the pointer against anything
                  other than a null pointer constant.
                  >
                  One would suspect that your code is not in fact C code, in
                  which case our most charitable assumption would be that you
                  have -accidently- posted your question to the wrong newsgroup.
                  >
                  But even if so, you need to figure out what it is supposed to
                  mean to delete a pointer to a storage area when you have returned
                  that pointer outwards. There are not many languages around
                  (-none- that I can think of right now) in which returning a pointer
                  to a memory block is understood to mean that the procedure
                  calling mechanism should take a -copy- of the storage pointed to
                  and put that copy somewhere for future use.
                  It amazed me that there are already about 5 people who have told him
                  this is C++ code and yet you feel the need to go lengths to belittle the
                  OP.

                  You did know there had been OT replies. You did know that it was
                  C++. One can only guess at your motives for posting such a long and
                  relatively useless reply.

                  Comment

                  • Malcolm McLean

                    #10
                    Re: Another dynamic memory doubt


                    "Richard" <devr_@gmail.co mwrote in message
                    news:fuv4f6$adf $2@registered.m otzarella.org.. .
                    roberson@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
                    >
                    >In article <fuutl3$ecb$1@a ioe.org>, pradeep <nospam@nospam. comwrote:
                    >>
                    >>>I have the following code,
                    >>
                    >>>char* MyClass::MyMeth od()
                    >>
                    >That line is a syntax error. The only place that a colon (':')
                    >can occur in a type description in C is as a bit-field length
                    >within a structure definition.
                    >>
                    >
                    It amazed me that there are already about 5 people who have told him
                    this is C++ code and yet you feel the need to go lengths to belittle the
                    OP.
                    >
                    You did know there had been OT replies. You did know that it was
                    C++. One can only guess at your motives for posting such a long and
                    relatively useless reply.
                    >
                    Unfortunately Walter's sort of reply - and we can all be clever Dicks to
                    people new to programming - encourages people like Antonius Twink to give
                    off-topic answers as a sort of compensation.
                    Why can't people just say "this is C++"?

                    --
                    Free games and programming goodies.


                    Comment

                    • Antoninus Twink

                      #11
                      Re: Another dynamic memory doubt

                      On 26 Apr 2008 at 11:39, Ben Bacarisse wrote:
                      Antoninus Twink <nospam@nospam. invalidwrites:
                      >In C++, ...
                      >
                      I won't point out the C++ errors you made (that would be to fall into
                      your trap)
                      If there were real errors (not just the usual not standard, not portable
                      bullshit) then point them out and cross-post to clc++ if you insist.

                      Comment

                      • Richard

                        #12
                        Re: Another dynamic memory doubt

                        "Malcolm McLean" <regniztar@btin ternet.comwrite s:
                        "Richard" <devr_@gmail.co mwrote in message
                        news:fuv4f6$adf $2@registered.m otzarella.org.. .
                        >roberson@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
                        >>
                        >>In article <fuutl3$ecb$1@a ioe.org>, pradeep <nospam@nospam. comwrote:
                        >>>
                        >>>>I have the following code,
                        >>>
                        >>>>char* MyClass::MyMeth od()
                        >>>
                        >>That line is a syntax error. The only place that a colon (':')
                        >>can occur in a type description in C is as a bit-field length
                        >>within a structure definition.
                        >>>
                        >>
                        >It amazed me that there are already about 5 people who have told him
                        >this is C++ code and yet you feel the need to go lengths to belittle the
                        >OP.
                        >>
                        >You did know there had been OT replies. You did know that it was
                        >C++. One can only guess at your motives for posting such a long and
                        >relatively useless reply.
                        >>
                        Unfortunately Walter's sort of reply - and we can all be clever Dicks
                        to people new to programming - encourages people like Antonius Twink
                        to give off-topic answers as a sort of compensation.
                        Why can't people just say "this is C++"?
                        or why not post nothing at all when they KNOW Santosh, Falconer or Default Luser
                        will correct them.

                        Comment

                        • Ben Bacarisse

                          #13
                          Re: Another dynamic memory doubt

                          Antoninus Twink <nospam@nospam. invalidwrites:
                          On 26 Apr 2008 at 11:39, Ben Bacarisse wrote:
                          >Antoninus Twink <nospam@nospam. invalidwrites:
                          >>In C++, ...
                          >>
                          >I won't point out the C++ errors you made (that would be to fall into
                          >your trap)
                          >
                          If there were real errors (not just the usual not standard, not portable
                          bullshit) then point them out and cross-post to clc++ if you insist.
                          There is nothing stopping you posting your code in comp.lang.c++ and
                          there is nothing I can do to stop you if you choose to do something so
                          daft as cross-posting C++ code in both groups, but you can't sucker me
                          into doing it for you.

                          --
                          Ben.

                          Comment

                          • Antoninus Twink

                            #14
                            Re: Another dynamic memory doubt

                            On 26 Apr 2008 at 10:24, santosh wrote:
                            Antoninus Twink wrote:
                            >There are several problems and misunderstandin gs in your code...
                            >
                            ><snip C++ code and response>
                            >
                            Nowhere in your post did you mention to the OP that there is in fact a
                            dedicated Usenet group for C++ where answers are likely to be more
                            correct than OT responses in other groups. Why is that? Do you
                            deliberately want the OP to remain ignorant of the best forum for help
                            with his problem and risk betting on possibly incorrect or outdated
                            advice in other groups?
                            There is never any shortage of people who point out "more appropriate
                            groups" (usually with considerable bile and hostility, but
                            that's by the by).
                            Answering questions on non-conforming C code is one thing but answering
                            questions on totally separate languages and other wildly OT matters
                            (like the recent thread on Ethernet cables) seems a deliberate tactic
                            to lower the S:N ratio and wreck this group.
                            Here are some of the things I discussed with my colleagues at lunch
                            yesterday: C programming; Java programming; tree data structures; a
                            problem with someone's car; the new Ubuntu release; national politics. I
                            can promise you that my group hasn't been "wrecked" by this terrible
                            "lowering of the S:N ratio". On the contrary, in real life discussions
                            are eclectic by their nature, and talking about other things besides the
                            intricate minutiae of the C standard actually help build a positive
                            community, and that's good for exchanging programming knowledge too.

                            Comment

                            • santosh

                              #15
                              Re: Another dynamic memory doubt

                              Antoninus Twink wrote:
                              On 26 Apr 2008 at 10:24, santosh wrote:
                              <snip>
                              >Answering questions on non-conforming C code is one thing but
                              >answering questions on totally separate languages and other wildly OT
                              >matters (like the recent thread on Ethernet cables) seems a
                              >deliberate tactic to lower the S:N ratio and wreck this group.
                              >
                              Here are some of the things I discussed with my colleagues at lunch
                              yesterday: C programming; Java programming; tree data structures; a
                              problem with someone's car; the new Ubuntu release; national politics.
                              I can promise you that my group hasn't been "wrecked" by this terrible
                              "lowering of the S:N ratio".
                              Why are you comparing a face-to-face group discussion with a newsgroup?
                              They are totally different beyond the basic fact that both are used for
                              exchange of ideas.
                              On the contrary, in real life discussions
                              ^^^^^^^^^^
                              <snip>

                              So anything further you say has no bearing for a newsgroup.

                              As I said, answering non-standard C questions is one thing but answering
                              questions on everthing under the Sun is only going to encourage newbies
                              and lurkers to start posting OT and drown the topical content.

                              There is also the fact that non-C answers are likely to have lower rate
                              of correctness, and this combined with deliberately concealing from the
                              newbie the existence of a dedicated group and inviting him to post
                              further non-C questions here is a disservice not only to the group
                              (which I understand that you don't like) but also to the newbie.
                              are eclectic by their nature, and talking about other things besides
                              the intricate minutiae of the C standard actually help build a
                              positive community, and that's good for exchanging programming
                              knowledge too.
                              No. Newsgroups are not communities. They are places to ask questions and
                              air ideas on the specified topic and receive responses. They don't
                              function like real-life informal communities or groups. They can be
                              better compared to a real-life support group. Do you also go to
                              Alcoholics Anonymous and complain of your C problems?

                              Comment

                              Working...