Thread: allocation method

  1. #1
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472

    allocation method

    i saw a code example for dynamic memory c++ and have used the method in this function to allocate memory, is it an advisable way to do it? i never saw it eactly like this or maybe i have and forgotten.

    Code:
    void GetDrawNumbers(int tot_nums, int drawnums[])
    {
        
        int allocsize = tot_nums;
        int* tempnums = new int[allocsize];
    
        //do stuff
    
        free(tempnums);
    
    
    }
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    No. new[] must be matched with delete [].

    Unless you have very specific reasons, you should be using a std::vector.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Free? not delete[]?

  4. #4
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    Free? not delete[]?
    haha, it is now delete, ay caramba, ta
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by rogster001
    haha, it is now delete, ay caramba, ta
    It is now delete? You must have missed a point that anon made:
    Code:
    void GetDrawNumbers(int tot_nums, int drawnums[])
    {
        std::vector<int> tempnums(tot_nums);
    
        //do stuff
    
        // look ma, no need to remember to free, delete or delete[]!
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    haha afraid i am a vector virgin lazy ole me... an it aint building for me like that maam, am looking up usage now,

    EDIT >

    this works, fine, am i doing anything wrong here? i am not handling the exception i know

    Code:
    void GetDrawNumbers(int tot_nums, int drawnums[])
    {
        int check = 0;
        int num = 0;
        int count = 0;
        bool dupe = false;
    
        std::vector<int> tempnums(tot_nums, 0); //this initialises to 0?
    
        while(count < tot_nums)
        {
            num = rand() % MAXNUMS + 1;
    
            for(check = 0; check < tot_nums; check++)
            {
                if(tempnums.at(check) == num)
                dupe = true;
            }
    
            if(!dupe)
            {
                drawnums[count] = num;
                tempnums.at(count) = num;
                count++;
            }
    
            dupe = false;
        }
    }
    Last edited by rogster001; 04-14-2010 at 05:15 AM. Reason: .
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by rogster001
    this works, fine, am i doing anything wrong here?
    It looks okay, though it may be easier to write:
    Code:
    void GetDrawNumbers(int total_nums, int drawnums[])
    {
        std::set<int> generated_nums;
    
        for (int i = 0; i < total_nums; ++i)
        {
            int num;
            do
            {
                num = rand() % MAXNUMS + 1;
            }
            while (!generated_nums.insert(num).second);
    
            drawnums[i] = num;
        }
    }
    Since you effectively want a set of generated numbers, you might as well use std::set. Then, you generate a pseudorandom number, and try and insert it into the set. If the insertion fails, you repeat the pseudorandom number generation and try again until insertion succeeds, in which case you fill in the next element of drawnums.

    Just a comment about the algorithm: this is likely to work well when MAXNUMS is large. If MAXNUMS is sufficiently small, it would be more efficient to populate an array with the integers in the range [1, MAXNUMS], shuffle the array, then pick the first total_nums elements.
    Last edited by laserlight; 04-14-2010 at 05:49 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    yes, point taken about the algorithm, that would be a much neater solution, i have written this sort of thing lots of times and that has never occured to me haha.

    Just one thing here, you mention the use of std::set, it just strikes me that the more i learn about C++ the less there is to do,! i understand about not reinventing wheels but, it seems like such a high level language compared to C, and i know this has been argued umpteen times in these pages, but all this std stuff its like C++ is just an editor for pre built functional components that you just assemble as required, like lego, and whats wrong with that...i dont know if anything is wrong .but i am just saying...
    and i suppose to commercial software writers this sort of thing is like a blessing, but then they have the benefit of knowing / understanding the way the function is working internally, beginners going straight into C++ can just use stuff blindly and never worry about what is going on, how it works, but then nobody worries about how their computer works in general, who cares which bit of electricity is at which junction at any one time, we just want to write documents etc
    Last edited by rogster001; 04-14-2010 at 06:18 AM.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  9. #9
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Programming generally is about getting a job done, not studying how things work under the hood (which, I'm sorry, you don't learn on your own by implementing naive algorithms with naive data structures either).
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by rogster001
    beginners going straight into C++ can just use stuff blindly and never worry about what is going on, how it works, but then nobody worries about how their computer works in general, who cares which bit of electricity is at which junction at any one time, we just want to write documents etc
    If beginners want to learn those, they should take the appropriate courses. Put it another way: would you require that everyone who wants to learn how to program first have a doctorate in particle physics? After all, people must learn about the building blocks of the universe in order to appreciate the building blocks of a computer, right?

    EDIT:
    But if you are trying to compare C and C++ in this department, both C and C++ are too high level. You should be complaining about how high level C is compared to assembly language, and then complain how mnemonics abstract what's really going on, compared to machine language.
    Last edited by laserlight; 04-14-2010 at 06:39 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    naive algorithms with naive data structures
    naive maybe, but it "gets the job done"
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  12. #12
    The larch
    Join Date
    May 2006
    Posts
    3,573
    May-be I was a bit harsh, but it is a possibility that the reinvented wheel turns out to be square (and if you never recognize it as such, you may not have learnt much).

    However, if you are drawing non-repeating random numbers, then this is the problem. At some point you should have learnt how new[] is matched with delete[] and going on to use this doesn't teach you anything new. (Every C++ programmer should know that.)

    And as laserlight says, new[] (and even malloc) are high-level abstractions hiding a complex machinery that actually gets you the memory.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  13. #13
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    Aye, i did know about the new and delete relationship, , i think it was missed as i had been looking at C examples and it was just an oversight, as far as non repeating random number generation goes then this is definitely reinvention of wheel as it is surely required a LOT, i just had never known there was a standard library solution for that.
    i tell you what it is, sometimes i feel like i am missing out on something. like the challenge of working out your own way of doing it, if someone says oh, just use std::, or whatever, and also its a bit like ready meals versus home cooked, at least you know what went in it haha, and sometimes i avoid it as i read somewhere say that this particular std::thing was inefficient or blah blah, so then i question myself as to whether i am choosing the correct tool...probably better the std:: library than my own humble attempts in all cases though aint it.
    and yes i agree, you could keep peeling back the layers on any library function i suppose.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  14. #14
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by laserlight View Post
    It looks okay, though it may be easier to write:
    Code:
    void GetDrawNumbers(int total_nums, int drawnums[])
    {
        std::set<int> generated_nums;
    
        for (int i = 0; i < total_nums; ++i)
        {
            int num;
            do
            {
                num = rand() % MAXNUMS + 1;
            }
            while (!generated_nums.insert(num).second);
    
            drawnums[i] = num;
        }
    }
    You could shorten that further too:
    Code:
    void GetDrawNumbers(int total_nums, int drawnums[])
    {
        std::set<int> generated_nums;
        while (generated_nums.size() < total_nums)
            generated_nums.insert(rand() % MAXNUMS + 1);
    
        std::copy(generated_nums.begin(), generated_nums.end(), drawnums);
    }
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. dynamic allocation from 1 instead of zero
    By cfdprogrammer in forum C Programming
    Replies: 27
    Last Post: 04-28-2009, 08:21 AM
  2. on method pointers and inheritance
    By BrownB in forum C++ Programming
    Replies: 2
    Last Post: 03-02-2009, 07:50 PM
  3. stuck on display method
    By shintaro in forum C++ Programming
    Replies: 2
    Last Post: 02-01-2009, 05:17 PM
  4. Overriding a method in C
    By DavidDobson in forum C Programming
    Replies: 1
    Last Post: 07-05-2008, 07:51 AM
  5. Replies: 2
    Last Post: 01-22-2008, 04:22 PM