Hi :)
I have a problem with the C++ dynamic memory allocation function NEW and DELETE.
When I first used it, it worked but there are times when I run my program that it crashes/terminates.
I check the pointer returned by NEW to see if the allocation was a success.
Each time my program crashes the pointer returned by NEW is not NULL.
I have tried using MALLOC and FREE and my program never crashes.
Please help me. I wanted to know the reason why NEW dont work sometimes while MALLOC works all the time.
My operating system is vista and the compiler I used is MinGW 3.4.2 with CodeBlocks IDE.
Bellow is sample code I tried .
#include <iostream>
using namespace std;
int main()
{
int * haha;
int counter = 0;
haha = 0;
haha = new (nothrow) int [44,000]; //allocate memory
if (haha != NULL)
{
for(counter = 0; counter < 5; counter++)
{
haha[counter] = counter + 1;
cout << "Allocated Mem 1v contains: " << haha[counter] << endl;
}
//free the allocated memory
delete[] haha;
}
else
{
cout << "Error memory allocation failed... Turning off application..." << endl;
}
return 0;
}
44,000 is not evaluated as forty-four thousand in C++, but as zero.
You should use 44000 with no thousands separator.
In C++, the comma operator is used to separate expressions and evaluate the last one, so in this case 000
Thank you man! I never noticed that! hahahah thank you :)