Reputation: 231
I was learning how to use the delete operator for dynamic arrays and i ran into some really strange problem. I tried two approach to write the same code - one worked but the other dint work. So, here is the code i tried
Method 1:-
#include <iostream>
using namespace std;
int main()
{
int *p = new int(2);
for(int i =0; i<2;i++)
{
cin>>p[i];
}
for(int i=0; i<2;i++)
{
cout<<p[i];
}
delete[] p;
system("pause");
}
//Error message - Heap Corruption detected. Can someone please explain me the reason of the error?
Method 2:- Using TypeDef
#include <iostream>
using namespace std;
typedef int arr[2];
int main()
{
int *p = new arr;
for(int i =0; i<2;i++)
{
cin>>p[i];
}
for(int i=0; i<2;i++)
{
cout<<p[i];
}
delete[] p;
system("pause");
}
//The above method works perfectly with no error. I am totally confused!!
Upvotes: 0
Views: 318
Reputation: 42828
new int(2)
allocates one int
that has the value 2
.
new int[2]
allocates an array of two int
s, with indeterminate values.
Upvotes: 2
Reputation: 24
in your first example you have:
int *p = new int(2);
which is initializing 1 pointer to the value of 2 rather than in your second example when you have a
new int[2];
where you're actually making 2 pointers.
Upvotes: 0
Reputation: 21130
You're calling the constructor of one int with the value of 2
not allocating two ints.
Use square brackets instead.
int *p = new int[ 2 ];
Upvotes: 2
Reputation: 234665
First case: you are only creating one int and assigning it the value of 2.
Then you treat it as an array with two elements. That's undefined behaviour. You need to use new int[2]. Your delete[] syntax is correct.
Your second example is far too obfuscated.
Upvotes: 2