0

Is there any way in a C++ program to check if a declaration of a variable wouldn't have proper resources? There are times when such a check is important.

example:

int i = 0; would normally work, but if the system didn't have resources for it (RAM/etc), it will fail/segfault/etc.

int *i; would likewise fail under this scenario, so new I don't believe would be a solution.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
ConfusedStack
  • 251
  • 3
  • 13
  • 3
    If you don't even have four bytes left on the stack, there isn't much you can do to remedy that anyway. You can't even call `exit` or unwind the stack. –  Feb 08 '14 at 14:02
  • 2
    The only time when automatic allocation of an `int` will fail is when you run out of stack. This is basically a question about [how to avoid that](http://stackoverflow.com/questions/12146201/how-to-handle-or-avoid-a-stack-overflow-in-c). – jrok Feb 08 '14 at 14:04
  • I would have thought `exit` would be more-or-less a `pop()`-type of command not requiring a `push()`. – ConfusedStack Feb 08 '14 at 15:15
  • @ConfusedStack First and foremost it's a function and needs some stack space to even be called, and probably some more to actually execute. Also, it can cause execution of several other functions (e.g. those registered with `atexit`). –  Feb 08 '14 at 15:25

1 Answers1

1

This "check" is performed when variable goes into scope or is initialized (it's "little" harder as compilers will optimize variables into registers reuse memory etc...) Handling memory errors when they happen is standard way. As OSes handle stack growth, and memory available to application - "atomic" operation is required. Assume scenario -

a) Your app checks if there is enough space on stack, the OS tells you go ahead, I still have some pages of real memory left...
b) Context switch occurs and some other app takes away all that precious memory
c) Your app tries to take space which is already in dirty hands of application b)

  • stack variable will produce stack overflow error
    Stack overflow errors are not standartized however. On windows you can find out stack overflow with __try __except blocks

  • heap variable allocated with new will produce bad_alloc (or call new handler) exception
    If you want to handle these cases simply catch exception thrown...

  • heap variable allocated with C functions will return null
    So check their return values
rAndom69
  • 755
  • 4
  • 7