title: The fprintf call throws EXC_BAD_ACCESS exception
body: <p>When I ran the APUE sample code shown below on my Mac, it throws a EXC_BAD_ACCESS exception. I have checked the file cursor, and it is in the right position 12. I even try to replace the <code>fprintf</code> with <code>fputc</code>. After that, it works fine and the exception is gone. But I want to know what happened out there and why.</p>
  <pre><code>#include &quot;apue.h&quot;
  
  #define BSZ 48
  
  int main(){
    FILE *fp;
    char buf[BSZ];
  
    memset(buf,'a',BSZ-2);
    buf[BSZ-2]='\0';
    buf[BSZ-1]='X';
    if ((fp = fmemopen(buf,BSZ,&quot;w+&quot;)) == NULL)
        err_sys(&quot;fmemopen failed&quot;);
    printf(&quot;initial buffer contents: %s\n&quot;,buf);
    fprintf(fp, &quot;hello, world&quot;);
    printf(&quot;before flush: %s\n&quot;, buf);
    fflush(fp);
    printf(&quot;after fflush: %s\n&quot;,buf);
    printf(&quot;len of string in buf = %ld\n&quot;,(long)strlen(buf));
  
    memset(buf,'b', BSZ-2);
    buf[BSZ-2]='\0';
    buf[BSZ-1]='X';
    fprintf(buf, &quot;hello, world&quot;);
  //  fputc('a',fp);
    fseek(fp,0,SEEK_SET);
    printf(&quot;after fseek: %s\n&quot;,buf);
    printf(&quot;len of string in buf = %ld\n&quot;, (long)strlen(buf));
  }
  </code></pre>
  <p>Console out put as below:</p>
  <pre><code>/Users/heping/Documents/APUE-Example-Code/stdio/cmake-build-debug/memstr
  initial buffer contents: 
  before flush: hello, world
  after fflush: hello, world
  len of string in buf = 12
  Exception: EXC_BAD_ACCESS (code=1, address=0x8)
  
  Process finished with exit code 9
  </code></pre>
  <p>Last stack frame like this: it seems like that something is wrong with the file lock, I think.</p>
  <p><a href="https://i.stack.imgur.com/kzG3I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kzG3I.png" alt="stak frame" /></a></p>