a strange code i dont understand!!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tamara omar
    New Member
    • Sep 2006
    • 23

    a strange code i dont understand!!

    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;
    }
  • m013690
    New Member
    • Sep 2006
    • 23

    #2
    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.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      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.

      Comment

      • m013690
        New Member
        • Sep 2006
        • 23

        #4
        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,

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          Originally posted by m013690
          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).

          Comment

          Working...