Thread: dynamic memory:

  1. #1
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499

    dynamic memory:

    I wanted to get more practice with dynamic array's so I decided to make a fun project. It takes the input until -1 is entered then displays the values entered followed by returned the memory back to the free store.

    Is this correct?

    Code:
     #include <iostream>
    
    using namespace std;
    
    int main(int argc, const char * argv[])
    {
        
        int n=0;
        int num=0;
        int *number=new int[n];
       
        
    cout<<"Enter and set of values and enter -1 to stop the program \n";
        
        while (num != -1) {
        cin>>num;
    
        number[n]=num;
        n++;
            
            if (num==-1) {
                for (int j=0; j<n; j++) {
                    cout<<number[j]<<"\n";
            
                }
            }
    
        }
        
    delete [] number;
        return 0;
    }

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    No, you haven't allocated any space for the array. Also, you should print the values after breaking out of the loop. Try this:
    Code:
    #include <iostream>
    using namespace std;
    int main(void)
    {
        int max_size = 1024;
        int n=0;
        int num=0;
        int *number=new int[max_size];
        cout<<"Enter a maximum of " << max_size << " values and enter -1 to stop the program \n";
        for(;;) {
            if(n == max_size)
            {
                cout<<"Sorry, no more room!\n";
                break;
            }
            cin>>num;
            if(num == -1)
                break;        
            number[n++]=num;
        }
        cout<<"Numbers entered:\n";
        for (int j=0; j<n; j++) {
            cout<<number[j]<<"\n";
        }    
        delete [] number;
        return 0;
    }
    Last edited by Sebastiani; 10-27-2013 at 10:36 AM.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by jocdrew21 View Post
    Is this correct?
    No since you allocate zero-length array - you have no place to store values.

    You should implement the above using std::vector first. Using raw dynamic memory would be next step
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Also, in your loop you're checking for -1 before the user input is even read.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  5. #5
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Didn't know I could use for loops like that
    Code:
    for(;;) { }
    How did I not allocate it any space? When I incremented
    Code:
     while (num != -1) {    cin>>num;
    
    
        number[n]=num;
        n++;
    I thought I was doing just that? Because
    Code:
    int *number=newint[n];
    Now before some says it, I know I am treating this kinda like a vector and it would be smarter to use a vector. I just am practicing with array's.

  6. #6
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by Sebastiani View Post
    Also, in your loop you're checking for -1 before the user input is even read.
    It i ok since initially num is initialized to 0...
    Problem lies later - when num is inserted into the array even if stop value of -1 was entered.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  7. #7
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Ok i was writing my comment while others were too. I just read what everyone wrote...

    Note taken.. I'll work on it some more… I really thought I had it.

  8. #8
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The code
    Code:
    int *number = new int[n]
    only happens once. When you change n, the compiler doesn't go back to this line and redo your initialization of number.

  9. #9
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Ok you guys were right, my complier now say:
    smart array dynamic Mohammad(3540) malloc: *** error for object 0x100103c50: pointer being freed was not allocated
    *** set a breakpoint in malloc_error_break to debug

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main(int argc, const char * argv[])
    {
        
        int n=0;
        int num;
        
       
    cout<<"Enter and set of values and enter -1 to stop the program \n";
        
        while (num != -1) {
        cin>>num;
        int *number=new int[n];
        number[n]=num;
        n++;
            
            if (num==-1) {
                for (int j=0; j<n; j++) {
                    cout<<number[j]<<"\n";
                    delete [] number;
                }
            }
        }
        
    
        return 0;
    }

  10. #10
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by jocdrew21 View Post
    How did I not allocate it any space?
    Since 'n' was initialized to zero, you were essentially doing this:

    Code:
    int *number=new int[0];
    So basically asking the system for zero ints. Indexing the array with a higher number does not somehow automagically allocate more space, it just equates to an out-of-bounds access (OOBA). That said, you could certainly design a custom class that would treat OOBA's as append requests where the internal memory was resized before returning. But we'll leave that for a later exercise...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by jocdrew21
    Now before some says it, I know I am treating this kinda like a vector and it would be smarter to use a vector. I just am practicing with array's.
    In that case, design and implement your own simplified dynamic array class, using std::vector for reference.
    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

  12. #12
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    I used a vector would this be correct? This is how I would do it if I had to. I just wanted to play with array's….

    Code:
     #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main(int argc, const char * argv[])
    {
        int num=0;
        int n=0;
        vector<int>easier;
        
        cout<<"Enter some random values and -1 to stop the program"<<endl;
        while (num!= -1) {
            
            cin>>num;
            
            easier.push_back(num);
            n++;
            
            if (num==-1) {
                for (int i=0; i<n; i++) {
                    cout<<easier[i]<<endl;
                    easier.erase(easier.begin(),easier.end());
                }
                
            }
        }
        return 0;
    }

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    This part is certainly wrong:
    Code:
    for (int i=0; i<n; i++) {
        cout<<easier[i]<<endl;
        easier.erase(easier.begin(),easier.end());
    }
    On the first iteration, you print easier[0], then you erase the entire range of the vector. Therefore, even if n was greater than 1, easier[1] ceases to exist, hence you access the vector out of bounds on the next iteration. You don't need to call erase at all.

    Furthermore, you don't need n: you can just call easier.size().
    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

  14. #14
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    laser light why is that I have it working and outputting the way I would like the way I wrote it, but it but when I use easier.size() I only output the last number. Granted I left the erase method too.

    I am not challenging you here just really curious. By the way, you have given me some of the best advice next to vart and white flags. You guys are really amazing. How long have you been programing?

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by jocdrew21
    why is that I have it working and outputting the way I would like the way I wrote it
    Undefined behaviour.

    Quote Originally Posted by jocdrew21
    but it but when I use easier.size() I only output the last number. Granted I left the erase method too.
    You probably only output the first number. Since you left the erase call in, on the next iteration, the size() member function returns 0, hence the loop ends.

    Quote Originally Posted by jocdrew21
    By the way, you have given me some of the best advice next to vart and white flags. You guys are really amazing.
    You're welcome

    Quote Originally Posted by jocdrew21
    How long have you been programing?
    13 years or so.
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic memory and realloc(), freeing memory
    By C_Sparky in forum C Programming
    Replies: 6
    Last Post: 10-06-2010, 07:55 PM
  2. Why use Dynamic Memory
    By appleGuy in forum C++ Programming
    Replies: 11
    Last Post: 08-28-2006, 02:46 PM
  3. static memory and dynamic memory
    By nextus in forum C++ Programming
    Replies: 1
    Last Post: 03-01-2003, 08:46 PM
  4. dynamic memory
    By cppdude in forum Windows Programming
    Replies: 15
    Last Post: 06-06-2002, 04:30 PM
  5. dynamic memory
    By falconetti in forum C Programming
    Replies: 2
    Last Post: 12-21-2001, 02:26 PM