title: In what cases I may lose access to pointer allocated by malloc?
body: <p>EDIT: Changed Title to ignore my assumption.</p>
  
  <p>I have a library, written in c, which uses posix message queue to pass pointers to some runtime data between threads.</p>
  
  <p>In cases where the data is coming from user application, everything seems to work fine, and I am able to access the data pointed by the pointer to a structure, coming from the message queue. </p>
  
  <p>Now, I have a special case where the library itself will do a malloc of one instance of the structure, set a flag and send it to the same queue. On the receiving end, the structure is empty and the flag is zero. Calling free on the pointer causes a crash.</p>
  
  <p>Here's code:</p>
  
  <pre><code>volatile s_thestruct * volatile data = malloc(sizeof(s_thestruct));
  data-&gt;flags = THE_FLAG;
  mq_send(handle, (char *)&amp;data, sizeof(s_thestruct *), 1)
  </code></pre>
  
  <p>And on the receiving end:</p>
  
  <pre><code>ssize_t read = mq_receive(handle, (char*)&amp;data, sizeof(s_thestruct*), NULL);
  if(read != sizeof(s_thestruct *))
  {
   // Error handling, no problems here
  }
  if(data-&gt;flags == THE_FLAG)
  {
  // Do something, never gets here
  }
  // Do something else, no it is not freed here
  
  // Finally
  free(data); // &lt;--CRASH
  </code></pre>
  
  <p>And I will get: </p>
  
  <pre><code>*** glibc detected *** /usr/bin/applicationthingy: free(): invalid pointer: 0x08053cf0 ***
  </code></pre>
  
  <p>Followed by dump.
  Within the memory map dump I find:</p>
  
  <pre><code>....
  08048000-0804a000 r-xp 00000000 08:01 802680     /usr/bin/applicationthingy
  0804a000-0804b000 r--p 00001000 08:01 802680     /usr/bin/applicationthingy
  0804b000-0804c000 rw-p 00002000 08:01 802680     /usr/bin/applicationthingy
  0804c000-0806f000 rw-p 00000000 00:00 0          [heap]
  b6e00000-b6e21000 rw-p 00000000 00:00 0 
  ....
  </code></pre>
  
  <p>So, anyone got any suggestions of what's going on here?</p>