Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C goto different function

Tags:

c

embedded

goto

I'm working with an embedded system where the exit() call doesn't seem to exist.

I have a function that calls malloc and rather than let the program crash when it fails I'd rather exit a bit more gracefully.

My initial idea was to use goto however the labels seem to have a very limited scope (I'm not sure, I've never used them before "NEVER USE GOTO!!1!!").

I was wondering if it is possible to goto a section of another function or if there are any other creative ways of exiting a C program from an arbitrary function.

void main() {
  //stuff
  a();

  exit:
     return;
}

void a() {
   //stuff

   //if malloc failed
   goto exit;
}

Thanks for any help.

like image 709
user1872099 Avatar asked Dec 03 '12 09:12

user1872099


1 Answers

Options:

  • since your system is non-standard (or perhaps is standard but non-hosted), check its documentation for how to exit.
  • try abort() (warning: this will not call atexit handlers).
  • check whether your system allows you to send a signal to yourself that will kill yourself.
  • return a value from a() indicating error, and propagate that via error returns all the way back to main.
  • check whether your system has setjmp/longjmp. These are difficult to use correctly but they do provide what you asked for: the ability to transfer execution from anywhere in your program (not necessarily including a signal/interrupt handler, but then you probably wouldn't be calling malloc in either of those anyway) to a specific point in your main function.
  • if your embedded system is such that your program is the only code that runs on it, then instead of exiting you could call some code that goes into an error state: perhaps an infinite loop, that perhaps flashes an LED or otherwise indicates that badness has happened. Maybe you can provoke a reboot.
like image 174
Steve Jessop Avatar answered Sep 28 '22 08:09

Steve Jessop