Note that there are some explanatory texts on larger screens.

plurals
  1. POA "free(): invalid next size (fast)" in C++
    text
    copied!<p>I just ran into a <code>free(): invalid next size (fast)</code> problem while writing a C++ program. And I failed to figure out why this could happen unfortunately. The code is given below.</p> <pre><code>bool not_corrupt(struct packet *pkt, int size) { if (!size) return false; bool result = true; char *exp_checksum = (char*)malloc(size * sizeof(char)); char *rec_checksum = (char*)malloc(size * sizeof(char)); char *rec_data = (char*)malloc(size * sizeof(char)); //memcpy(rec_checksum, pkt-&gt;data+HEADER_SIZE+SEQ_SIZE+DATA_SIZE, size); //memcpy(rec_data, pkt-&gt;data+HEADER_SIZE+SEQ_SIZE, size); for (int i = 0; i &lt; size; i++) { rec_checksum[i] = pkt-&gt;data[HEADER_SIZE+SEQ_SIZE+DATA_SIZE+i]; rec_data[i] = pkt-&gt;data[HEADER_SIZE+SEQ_SIZE+i]; } do_checksum(exp_checksum, rec_data, DATA_SIZE); for (int i = 0; i &lt; size; i++) { if (exp_checksum[i] != rec_checksum[i]) { result = false; break; } } free(exp_checksum); free(rec_checksum); free(rec_data); return result; } </code></pre> <p>The macros used are:</p> <pre><code>#define RDT_PKTSIZE 128 #define SEQ_SIZE 4 #define HEADER_SIZE 1 #define DATA_SIZE ((RDT_PKTSIZE - HEADER_SIZE - SEQ_SIZE) / 2) </code></pre> <p>The struct used is:</p> <pre><code>struct packet { char data[RDT_PKTSIZE]; }; </code></pre> <p>This piece of code doesn't go wrong every time. It would crash with the <code>free(): invalid next size (fast)</code> sometimes in the <code>free(exp_checksum);</code> part. </p> <p>What's even worse is that sometimes what's in <code>rec_checksum</code> stuff is just not equal to what's in <code>pkt-&gt;data[HEADER_SIZE+SEQ_SIZE+DATA_SIZE]</code> stuff, which should be the same according to the watch expressions from my debugging tools. Both <code>memcpy</code> and <code>for</code> methods are used but this problem remains.</p> <p>I don't quite understand why this would happen. I would be very thankful if anyone could explain this to me.</p> <p><strong>Edit:</strong></p> <p>Here's the do_checksum() method, which is very simple:</p> <pre><code>void do_checksum(char* checksum, char* data, int size) { for (int i = 0; i &lt; size; i++) { checksum[i] = ~data[i]; } } </code></pre> <p><strong>Edit 2:</strong></p> <p>Thanks for all. </p> <p>I switched other part of my code from the usage of STL queue to STL vector, the results turn to be cool then. </p> <p>But still I didn't figure out why. I am sure that I would never pop an empty queue.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload