Reputation: 3
Can somebody point out the problem with this code (for resizing a dynamic array). I am using Visual Studio 2013 to run the code. It gives a runtime error i.e. heap corruption detected after normal block (a number) at (memory address). CRT detected that the application wrote to the memory after the end of heap buffer
.
I am to use the technique mentioned below and not any standard library function or vector for resizing the array:
#include<iostream>
using namespace std;
int * rg(int *, int, int);
int main()
{
int len = 1;
int * x = new int[len];
int i = 0;
int y = 0;
while (getchar() != 'q')
{
cin >> y;
if (i == 0)
x[0] = y;
else
{
x = rg(x, len, y);
len++;
}
cout << len;
i++;
}
cout << endl;
for (int i = 0; i < len; i++)
{
cout << x[i] << endl;
}
}
int * rg(int*x, int len, int val)
{
int * temp = x;
x = new int[];
for (int i = 0; i < len; i++)
{
x[i] = temp[i];
}
x[len] = val;
delete[]temp;
return x;
}
Upvotes: 0
Views: 108
Reputation: 150
You didn't include library that has getchar
. Add #include <cstdio>
at the beginning.
Second thing is that after grabbing the first number you don't increase len
, which causes the second input overwrite the first one. The last input is doubled at the end.
Third. When allocating memory, the compiler needs to know how much it has to allocate. You need to specify that in x = new int[]
.
Upvotes: 2
Reputation: 145214
x = new int[];
is invalid as standard C++ and shouldn't compile.
Upvotes: 3