Thread: Error Handling Advice Wanted

  1. #1
    Old Fashioned
    Join Date
    Nov 2016
    Posts
    137

    Question Error Handling Advice Wanted

    Say I have:

    Code:
    int sl_find(StringList *pSl, const char *str)
    {
        if(NULL == pSl || NULL == str)
        {
            return FAIL;
        }
        size_t i;
        for(i = 0; i < pSl->size; i++)
        {
            if(strcmp(pSl->data[i], str) == 0) return i;
        }
        return -2;
    }
    Where #define FAIL -1

    Its purpose is to locate a substring in the stringlist. If we find, we return the position. If we don't find, we return -1. What would you return in an error case such as NULL input ptrs? I don't want to return -1 becausae that would be ambiguous with "not found" but -2 is also not super conventional. I know an alternative is to use an output param but that feels heavy and a bit untuitive to either store the index or an error code.
    Just high level, how do you reason about these types of things?
    Not necessarily specific to this exact code. I've looked at for example the standard string.h functions and the return codes don't seem to be entirely consistent throughout.
    If I was homeless and jobless, I would take my laptop to a wifi source and write C for fun all day. It's the same thing I enjoy now!

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    870
    IMO, it would be pretty pointless to constantly check for NULL pointers and return some kind of code to the caller in every function that receives a pointer. The caller can ensure his inputs are not NULL in the first place. If they screw up with that who's to say they won't screw up in testing for your special value?

    It's more usual to do something like this so that you can have the NULL check in place for testing but remove it later on.
    Code:
    int sl_find(StringList *pSl, const char *str)
    {
        assert(pSl && str);
        for (size_t i = 0; i < pSl->size; i++)
            if (strcmp(pSl->data[i], str) == 0)
                return i;
        return -1; // don't name this; -1 is good enough
    }
    Can you demonstrate a couple of those inconsistencies that you found in the standard library implementation that you studied? What exactly do you mean?
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 06-15-2019, 09:09 PM
  2. Need Advice on File Handling
    By Gaurav Singh in forum C Programming
    Replies: 3
    Last Post: 10-24-2011, 11:14 PM
  3. Invoicing Shareware - Advice Wanted
    By Davros in forum A Brief History of Cprogramming.com
    Replies: 3
    Last Post: 07-09-2003, 01:57 AM
  4. SPAM. Advice wanted.
    By Davros in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 07-16-2002, 09:09 AM

Tags for this Thread