title: Is a strlen call in snprintf causing this segfault?
body: <p>I have a <code>void *</code>, call it <code>data</code>, whose length I know, but is not null terminated.  I make a call like this <code>snprintf(line, sizeof(line), "%*s", n, (const char*)data)</code> where <code>n</code> is the known length.  Almost always this works, but occasionally it results in a segfault.  </p>
  
  <p>Whenever the segfault occurs, the back trace says the problem is inside strlen.  And when I print <code>data</code> inside gdb, I see something like this </p>
  
  <pre><code>(gdb) p n
  $1 = 88
  (gdb) p (const char*) data
  $2 = 0x1d752fa8
  "JASDF" ... "ADS"&lt;Address 0x1d753000 out of bounds&gt;
  (gdb) p 0x1d753000-0x1d752fa8
  $3 = 88
  </code></pre>
  
  <p><code>data</code> is indeed 88 characters, but isn't null terminated, in fact, it seems that it lies right up against a segment.  My guess is that snprintf is always called strlen on data and I usually get lucky in that even though <code>data</code> isn't null terminated, there is a <code>\0</code> before I hit the segment and then occasionally I get unlucky and it is.  Is that right?  If so, what's the work around?</p>
  
  <p>This is what the stack trace looks like</p>
  
  <pre><code>#0  0x0000003c8927839e in strlen () from /lib64/libc.so.6
  #1  0x0000003c89246749 in vfprintf () from /lib64/libc.so.6
  #2  0x0000003c8926941a in vsnprintf () from /lib64/libc.so.6
  #3  0x0000003c8924d0a3 in snprintf () from /lib64/libc.so.6
  </code></pre>
  
  <p><strong>EDIT</strong> To answer my own question about the work around, strncpy is a more appropriate function to call.  I used snprintf by habit.</p>