Home > OS >  In a library, should I check if pointers are valid?
In a library, should I check if pointers are valid?

Time:02-20

I've wondered this for a while and the necessity of checking whether pointers are valid or not in my own library is even necessary. Should I just expect the user to pass in the correct pointers because it's their job if they're using the library?

For example if I have a library which allocates and returns a structure

struct some_context{
    uintptr_t somedata;
};
struct some_context* createsomecontext(void){
    return malloc(sizeof(struct some_context));
}

But then I want to operate on that structture

void dosomethingwithsomecontext(struct some_context* ctx){
    //which is more valid here?
    assert(ctx);
    
    //or
    if(!ctx)
        return;
    
    //do something with ctx
}

Does it make more sense to call assert, or check if the structure is valid and return if it isn't? Should I not even bother with checking the pointer and just assume the user is going to do the right thing? And same thing with cleanup

void destroysomecontext(struct some_context* ctx){
    //Which is more valid?
    assert(ctx);
    
    //or
    if(!ctx)
        return;
    
    //do cleanup
}

What's more appropriate? assert, if ,or neither? Similarly if I'm even writing a function to operate on a string?

void dosomestringoperation(char* str){
    assert(str);
    //or
    if(!str)
        return;
    
}

Should libraries ever do these checks ? At least in user mode, I can understand in the kernel since every device has access to the global memory and can cause a crash by not checking but does that imply even usermode applications should check for security/sanity reasons?

CodePudding user response:

Generally one assumes that pointers are valid, especially given that, except for null pointers, you have no way to tell if a passed pointer is valid for real (what if you are given a pointer to unallocated memory, or to wrong data?).

An assert (possibly one that is active even in release builds, though) is a nice courtesy to your caller, but that's just it; you are probably going to crash anyway when trying to dereference it, so whatever.

By all means, though, do not silently return if you get a null pointer: you are hiding a logical error under the rug, making it harder to debug for your caller.

  •  Tags:  
  • c
  • Related