title: Segfault on memcopy, also can anyone explain C syntax in this code?
body: <p>I am trying to debug a piece of code written by someone else that results in a segfault sometimes, but not all the time, during a memcpy operation.</p>
  
  <p>Also, I would dearly appreciate it if anyone could give me a hand in translating what's going on in a piece of code that occurs before the memcpy.</p>
  
  <p>First off, we have a function into which is being passed a void pointer and a pointer to a struct, like so:</p>
  
  <pre><code>  void ExampleFunction(void *dest, StuffStruct *buf)
  </code></pre>
  
  <p>The struct looks something like this:</p>
  
  <pre><code>typedef struct {
     char *stuff;
     unsigned int totalStuff;
     unsigned int stuffSize;
     unsigned int validStuff;
  
  } StuffStruct;
  </code></pre>
  
  <p>Back to ExampleFunction. Inside ExampleFunction, this is happening:</p>
  
  <pre><code>void *src;
  int numStuff;
  numStuff = buf-&gt;validStuff;
  src = (void *)(buf-&gt;stuff);
  </code></pre>
  
  <p>I'm confused by the above line. What happens exactly when the char array in buf->stuff gets cast to a void pointer, then set as the value of src? I can't follow what is supposed to happen with that step. </p>
  
  <p>Right after this, the memcpy happens:</p>
  
  <pre><code>memcpy(dest, src, buf-&gt;bufSize*numStuff)
  </code></pre>
  
  <p>And that's where the segfault often happens. I've checked for dest/src being null, neither are ever null. </p>
  
  <p>Additionally, in the function that calls ExampleFunction, the array for dest is declared with a size of 5000, if that matters. However, when I printf the value in buf->bufSize*numStuff in the above code, the value is often high above 5000 -- it can go up as high as 80,000 -- WITHOUT segfaulting, though. That is, it runs fine with the length variable (buf->bufSize*numStuff) being much higher than the supposed length that the dest variable was initialized with. However, maybe that doesn't matter since it was cast to a void pointer?</p>
  
  <p>For various reasons I'm unable to use dbg or install an IDE. I'm just using basic printf debugging. Does anyone have any ideas I could explore? Thank you in advance.</p>