While develop mobile App(limited memory about 2Mb or less), on malloc() fail, I have added a callback to report the error to UI, but the successive code still need to check the return value of malloc(), this may cause a lot of dirty code(check whether the returned memory is NULL or the false return code caused by allocation fail). is there a elegant way to terminate the successive code without exit() the whole App?
While develop mobile App( limited memory about 2Mb or less ), on malloc() fail,
Share
Do you mean ‘is there an elegant way to continue after memory allocation failure’?
Yes, there is, sort of, but it’s quite difficult to do right. By playing with
setjmpandlongumpyou can give yourself some sort of emergency recovery system a little akin to try/catch, but you have to be extremely careful to clean up as you pass up the call stack.Moreover, until your cleanup starts actually cleaning up allocated memory, any subsequent call to malloc is liable to fail.
Mostly, elegant is going to involve making sure you pass the error status back up the call stack though, and deal with it everywhere.