Thread: Dynamically allocating memory

  1. #1
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321

    Dynamically allocating memory

    Hello,

    I am trying to allocate an array, store some int values in it, and then print them out.
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
    	
    	int size;
    	cout<<"\nEnter no. of variables:";
    	cin>>size;
    	int *ptr=new int[size];
    	for(int i=0;i<size;i++,ptr++)
    	{
    		cout<<endl<<"Value of ptr["<<i<<"]=";
    	    cin>>*ptr;
    	}  
    	ptr-=size;
    	for(int i=0;i<size;i++,ptr++)
    	    cout<<endl<<"ptr["<<i<<"]="<<*ptr;
    		
    	delete[] ptr;
    	return 0;
    }
    It is giving output like this:
    Code:
    Enter no. of variables:3
    value of ptr[0]=56
    value of ptr[1]=89
    value of ptr[2]=4
    
    ptr[0]=56
    ptr[1]=89
    segmentation fault (core dumped)
    
    
    -----------------------------------------------
    Program exited with code:139
    Press return to continue
    Please point out what's wrong in the code and what is segmentation fault ?

    Thank you.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The seg fault could be because you attempt to delete[] a pointer that points to a non-existent object. The problem is that you are modifying ptr when it is supposed to point to the first element of the array.

    For a solution, I suggest that you just use array indexing:
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
        unsigned int size;
        cout << "\nEnter no. of variables:";
        cin >> size;
        int* ptr = new int[size];
        for (unsigned int i = 0; i < size; ++i)
        {
            cout << endl << "Value of ptr[" << i << "]=";
            cin >> ptr[i];
        }
    
        for (unsigned int i = 0; i < size; ++i)
            cout << endl << "ptr[" << i << "]=" << ptr[i];
    
        delete[] ptr;
        return 0;
    }
    Oh yes, why are you not using a std::vector instead?
    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

  3. #3
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    yes thanks. array indexing is easier.

    I also got my original code running by adding
    Code:
    ptr-=size
    before
    Code:
    delete[] ptr
    Oh yes, why are you not using a std::vector instead?
    I don't know what vectors are. I couldn't find vectors in the tutorials I am following.(?)

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    maybe it is time to replace your tutorial?
    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

  5. #5
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    sure I will, please suggest..

  6. #6
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    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
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I also got my original code running by adding
    I did not want to suggest that as it is rather fragile. With such a technique, not only must you carefully match your new[] with a delete[], but you must keep track of where exactly ptr is pointing so you can reset it as needed.

    maybe it is time to replace your tutorial?
    Indeed. You would do better to learn how to use a std::vector before you learn how to use dynamically allocated arrays. I suggest borrowing Accelerated C++ by Koenig and Moo from your local library.
    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
    Join Date
    Sep 2006
    Posts
    835
    The variable size should be a std::size_t (defined in <cstddef>) instead of an unsigned int, since that's the proper type for an array index (though it might happen to be the same type on your platform).

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The variable size should be a std::size_t (defined in <cstddef>) instead of an unsigned int, since that's the proper type for an array index (though it might happen to be the same type on your platform).
    That's true, though for such small values as expected from user input it would make no difference besides a possible compiler warning.
    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. Replies: 60
    Last Post: 01-09-2009, 01:09 PM
  2. Dynamically allocating memory...
    By Junior89 in forum C++ Programming
    Replies: 28
    Last Post: 05-08-2007, 10:17 PM
  3. Dynamically allocated memory
    By ^xor in forum Linux Programming
    Replies: 9
    Last Post: 06-28-2005, 11:42 AM
  4. allocating memory in constructor
    By Micko in forum C++ Programming
    Replies: 3
    Last Post: 08-25-2004, 07:45 AM
  5. Checking if memory has been dynamically allocated
    By Xzyx987X in forum C Programming
    Replies: 28
    Last Post: 03-14-2004, 06:53 PM