title: In a library, should I check if pointers are valid?
body: <p>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?</p>
  <p>For example if I have a library which allocates and returns a structure</p>
  <pre><code>struct some_context{
      uintptr_t somedata;
  };
  struct some_context* createsomecontext(void){
      return malloc(sizeof(struct some_context));
  }
  </code></pre>
  <p>But then I want to operate on that structture</p>
  <pre><code>void dosomethingwithsomecontext(struct some_context* ctx){
      //which is more valid here?
      assert(ctx);
      
      //or
      if(!ctx)
          return;
      
      //do something with ctx
  }
  </code></pre>
  <p>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</p>
  <pre><code>void destroysomecontext(struct some_context* ctx){
      //Which is more valid?
      assert(ctx);
      
      //or
      if(!ctx)
          return;
      
      //do cleanup
  }
  </code></pre>
  <p>What's more appropriate? assert, if ,or neither?
  Similarly if I'm even writing a function to operate on a string?</p>
  <pre><code>void dosomestringoperation(char* str){
      assert(str);
      //or
      if(!str)
          return;
      
  }
  </code></pre>
  <p>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?</p>