When I run it, half the time I get "exception: bad allocation", and in the other half I get six 3's but the last is a garbage value. Does anyone know why? I'm using Visual C++ 2008. It works fine when size is less than 7.
Code:
void print_array(ostream& os, int* a, int n)
{
for (int i = 0; i < n; i++) {
cout << a[i] << "\n";
}
}
int main()
try {
const int size = 7;
int* p2 = new int(size);
for (int i = 0; i < size; i++) {
p2[i] = 3;
}
print_array(cout, p2, size);
cin.get();
return 0;
}
catch(exception& e) {
cerr << "exception: " << e.what() << '\n';
keep_window_open("q");
return 1;
}
catch (...) {
cerr << "Some exception\n";
keep_window_open("q");
return 2;
}