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.

4
  • 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. Commented Feb 8, 2014 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. Commented Feb 8, 2014 at 14:04
  • I would have thought exit would be more-or-less a pop()-type of command not requiring a push(). Commented Feb 8, 2014 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). Commented Feb 8, 2014 at 15:25

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.