int main()
{
int *array = new int; //Should provide space to store only one integer right?
for(int i =0; i < 10; i++)
{
cout << "Assigning" << i << "th value\n";
array[i] = i + 1;
}
for(int i = 0; i < 10; i++)
cout << array[i] << '\t';
delete array;
cout << '\n';
return 0;
}
Output
Assigning0th value
Assigning1th value
Assigning2th value
Assigning3th value
Assigning4th value
Assigning5th value
Assigning6th value
Assigning7th value
Assigning8th value
Assigning9th value
1 2 3 4 5 6 7 8 154274097 154405171
I know pointer size on my system is 8 bytes, checked with sizeof(int*)
and integers take 4 bytes. I want to know how many chunks of memory in heap or free store (like literally boxes they use to teach students) does int* array = new int
created, because books say I can store just one integer in it; to store more(like 10 ints) I need to do int* array = new int[10]
. So how does this memory location pointed to by array
can store 8 integers instead of one. Please note, I ran for
loop 10 times as shown. Please tell me why are there just 2 garbage values, instead of 9 (since new
should only allocate one integer worth space). Using Ubuntu with g++ 9.3.0.