Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use goto fail for error handling and fix some memory leaks on the way #100

Merged
merged 5 commits into from
Feb 7, 2017

Conversation

FSMaxB
Copy link
Collaborator

@FSMaxB FSMaxB commented Feb 7, 2017

This replaces many different exit paths out of some functions with only one in case of errors.

This way it is much easier to reason about the code and properly manage allocated resources (and it actually fixes some memory leaks).

This relates to #56

Makes the control flow easier to reason about and fixes a few potential
memory leaks.
Makes the control flow easier to reason about and fixes a few potential
memory leaks.
Makes the control flow easier to reason about and fixes a few potential
memory leaks.
Simplify error handling using goto fail and improve some names.
@benlachman
Copy link

Careful with goto fail. It has a song written about it's ability to bite you: https://www.youtube.com/watch?v=tQms037U72w

@FSMaxB
Copy link
Collaborator Author

FSMaxB commented Feb 7, 2017

@benlachman I'm fully aware of the potential problems with goto fail.

The problem that Apple had in it's SSL library cannot happen in cJSON because we always use curly braces in if conditions.

There is the saying that goto is harmful, but it is not harmful in general, because there are about two legitimate use cases, one of which is goto fail.

The advantage of goto fail is that you can use a programming pattern where you allocate all resources at the beginning of a function and only ever free them in the fail section, this makes double frees and memory leaks much less likely. (and in this case, there have been several memory leaks).

If you add a new allocation at the beginning of a function, you really don't want to update every single if condition that returns from the function and add the call to free to it.

@benlachman
Copy link

@FSMaxB: Good. I just wanted to put it out there since it does have a history. Curly braces around all conditionals and loops are the way to go. 👍🏿

@FSMaxB FSMaxB merged commit 7119a16 into master Feb 7, 2017
@FSMaxB FSMaxB deleted the goto-fail branch February 7, 2017 20:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants