title: How can I convert to size_t from int safely?
body: <p>Assigning an int to a size_t (or using it in malloc) in GCC produces the following warning:</p>
  
  <blockquote>
    <p>warning: conversion to 'size_t' from 'int' may change the sign of the result [-Wsign-conversion]</p>
  </blockquote>
  
  <p>To solve this, I would like to wrap the conversion in a function that first checks if the conversion is valid, then does the cast.</p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>/* Convert int src to size_t dst. */
  /* Assumes dst points to valid size_t address. */
  int safe_size_t_from_int(size_t *dst, int src) {
      if(src &lt; 0) return SAFE_ERROR_NEGATIVE;
      if(SIZE_MAX &lt; INT_MAX) {
          if(src &gt; (int)SIZE_MAX) return SAFE_ERROR_OVERFLOW;
      }
      *dst = (size_t)src;
      return SAFE_SUCCESS;
  }
  </code></pre>
  
  <p>Am I missing anything? Is there a library with safe conversions that already exists?</p>
  
  <p>The closest thing I can find is <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ff521693%28v=vs.85%29.aspx" rel="noreferrer">Microsoft Intsafe.h</a>, but it appears to be for Win32 types only.</p>
  
  <p><strong>EDIT</strong> Modified as per chux' comment.</p>