Skip to content

Instantly share code, notes, and snippets.

@loderunner
Created April 20, 2017 14:25
Show Gist options
  • Save loderunner/70f16b8b6a5b37f01bee0bba22f2e83a to your computer and use it in GitHub Desktop.
Save loderunner/70f16b8b6a5b37f01bee0bba22f2e83a to your computer and use it in GitHub Desktop.

GOTO challenge

Problem

Suppose a function that does the following, assuming all operations can fail and none can block:

  • Allocate XXX bytes of memory (on the heap)
  • Open file for reading
  • Read file into allocated buffer
  • Acquire lock
  • Do stuff with data now in memory

Each of the steps in italics has a corresponding "cleanup" before exiting the function:

  • Free memory
  • Close file
  • Release lock

GOTO solution

Arguably, one of the cleanest solutions to design this function is using goto:

Allocate memory
if fail
    set error code
    goto end

Open file
if fail
    set error code
    goto end
    
Read data
if fail
    set error code
    goto end

Try to acquire lock
if fail
    set error code
    goto end
    
// Do the stuff

end:
if lock acquired
    release lock
if file opened
    close file
if mem allocated
    release mem
    
return error code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment