sophiakoulen / mathematical-expression-parser

Computing the result of a mathematical expression containing floating point numbers
0 stars 1 forks source link

How important is checking malloc protection in this project? #7

Open sophiakoulen opened 1 year ago

sophiakoulen commented 1 year ago

We could argue that in this project we could just assume malloc will always succeed so that we can focus on the parsing aspect. I feel like elegantly handling each malloc failure will add extra code and maybe will make us rethink our error handling. However, we'll have to deal with it in further projects so we might as well take malloc failure into account and try external tools to help with that.

znichola commented 1 year ago

It's a good point, I think we can add what you have and get back to it later. It's a good point about the extra code length, at least at this relatively early stage it adds extra lines but things are still very changeable. That said it's a very interesting approach to overwrite the standard malloc and force a failure. For sure something to keep in mind for minishell.

znichola commented 1 year ago

I think a relatively easy way to protect against malloc failure is to use exit() and a wrapper for malloc.

in pseudo code

def malloc_wrapper
    do_malloc
    if malloc == failure
        clean_up     // call our custom function that frees what needs it, this is good practice, but not really needed
        print_error  // print a hit as to what malloc failed
        exit(1)      // kill the program and this also frees anything that still has a pointer in memory, hence clean_up not needed
    return malloced_thing
sophiakoulen commented 1 year ago

I just saw that's how they do it in GNU readline. You can check out the code here (https://github.com/JuliaAttic/readline/blob/master/xmalloc.c)