-3

My question is very very clear .. if it didn't collect garbage what will happen
And why that thing does not happen in c++

Hunar
  • 47
  • 7

2 Answers2

0

If stale objects are not collected, you will run into an OutOfMemoryError. And this will also happen in C++, if you don't clean up old data (the error is probably not called OutOfMemoryError, but the consequences are the same i guess).

dunni
  • 38,210
  • 8
  • 94
  • 96
  • 1
    In C, `malloc()` will fail and return NULL. In C++, `new` will throw `bad_alloc` unless `(nothrow)` was specified, in which case NULL will be returned. – Mike Harris Apr 02 '16 at 13:38
  • Ok, i don't have that much experience with C/C++ (it's been already a few years). Will the program crash, or can you somehow catch those errors and workaround that? – dunni Apr 02 '16 at 13:52
  • @dunni If that is what you wanted to know, you should have asked that – Raedwald Apr 02 '16 at 14:07
  • @dunni See http://stackoverflow.com/questions/14376924/should-i-catch-outofmemoryerror – Raedwald Apr 02 '16 at 14:18
  • @dunni It's very much like Java, in some ways. If an exception is thrown and not handled, the program will terminate. If a NULL pointer is returned and you attempt to dereference it, the program will most likely crash (e.g., bus error). There's not really any such thing as a NullPointerException in C/C++. You can catch these errors in C/C++, and in the case of C (i.e., `malloc()`) you most definitely should! – Mike Harris Apr 02 '16 at 14:18
0

It does happen in C/C++. In a different way. In C/C++ the responsibility lies more with the programmer to keep track of memory allocated and to free it. Programmers have direct access to memory in the form of pointers. In java it is all hidden from programmer. You don't need to keep track of memory, JVM does it for you in the form of garbage collection. That does not mean you can allocate memory to objects wily-nily. Global objects are retained for long time and if GC cannot reach them in time, the memory goes beyond limit and OutOfMemoryException happens.

M S
  • 109
  • 4