I am new to C++ and is learning about dynamic memory allocation. I wrote a code to learn the use of "new" operator but is having problem with the output.
Here's the basic code which i wrote:
#include<iostream>
#include<new>
using namespace std;
main()
{
int *p,i,m;
cout<<"how many values u want to insert?"<<"\n";
cin>>i;
cout<<"\n";
p=new (nothrow) int[i];
if(p == 0)
cout << "Error: memory could not be allocated";
for(m=0;m<i;m++)
{
cout<<"Insert value no."<<m+1<<" :\n";
cin>>p[m];
cout<<"\n";
}
for(m=0;m<i;m++)
{
cout<<"Ur value no."<<m+1<<" is: "<<p[m]<<"\n";
delete [] p;
}
}
The problem with the output is that the second value returns garbage. For ex: if the user enters that they want to insert 3 values with inputs 5,6 and 7 as the three values the outputs are 5, 84569712 and 7. I am unable to understand why the 2nd value is so abrupt. Help me with this please.
Below is the link of output image file: https://www.dropbox.com/s/54qfh1kmzq37ypi/output%20image.PNG
#1: Was it so hard to use the provided code tags? Please use them next time. >_>
#2: C++ does not support default-int, meaning main() needs to be explicitly declared as an int.
#3: Although your program will complain if it can't allocate memory, it will keep going as if everything was A-OK. Your program should exit in this circumstance.
#4: delete [] gets called in a loop. You probably meant to move that to after the end of the loop it's currently in.
#5: I don't know why you're getting the abrupt result. What SHOULD happen is that the program should crash after outputting the second value because you're trying to free memory that the program doesn't own.