By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,778 Members | 1,957 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,778 IT Pros & Developers. It's quick & easy.

a strange code i dont understand!!

P: 23
i want to know what happens when we run this code below?

void main(){
long *p=new long[200];
while(p)
p=new long[1000];
cout<<*p<<endl;
}
Sep 30 '06 #1
Share this Question
Share on Google+
4 Replies


P: 23
Doesn't do much of anything productive, that's for sure. All it will actually do is continue allocating new memory until it has used up all that the system has available, at which point is will throw an exception and terminate program execution.

It's not quite an infinite loop, in that it will finally exit when the system is no longer able to allocate more memory to the pointer 'p'. At that point, though, it will probably break out of the loop, not by 'p' being NULL, but because it throws an unhandled exception.
Sep 30 '06 #2

Banfa
Expert Mod 5K+
P: 8,916
Not quite true

because it is written with

void main()

this program actually invokes undefined behaviour. This means it does absolutely anything it wants to including the behaviour you suggest but also including anything from printing "Hello World" to contacting the USA MOD computers hacking into them and starting World War III.

As you can see undefined behaviour is not a good thing to invoke due to it's rather random nature.


I do conceed that the most likely result is what you suggest though.
Sep 30 '06 #3

P: 23
Is that because of the 'void'?

In my first programming class (years back) they taught us to use void. It wasn't until several semesters later that I heard somewhere along the way that 'int' is considered better. Can't say I recall the reason though, but I'd be curious to hear if you have an explanation.

Thanks,
Oct 1 '06 #4

Banfa
Expert Mod 5K+
P: 8,916
Is that because of the 'void'?

In my first programming class (years back) they taught us to use void. It wasn't until several semesters later that I heard somewhere along the way that 'int' is considered better. Can't say I recall the reason though, but I'd be curious to hear if you have an explanation.
Yes it's because of the void, main should be written in C and C++

int main(int argc, char **argp)
{
}

or alternitively in C++ only

int main()
{
}

And the reason is because that is what the standard specifies (also the code alling main is expecting a return value).
Oct 1 '06 #5

Post your reply

Sign in to post your reply or Sign up for a free account.