Note that there are some explanatory texts on larger screens.

plurals
  1. POrealloc after free problem ("realloc: invalid next size")
    primarykey
    data
    text
    <p>I've got a strange problem with realloc, here's my code (relevant parts only, too big to post the full code here):</p> <pre><code>char * print_bar(struct bar *ptr) { char *buf = NULL; char *buftmp = NULL; size_t size = 60; int count = 0; if (ptr) { while (count == 0 || count+4 &gt;= size) { buftmp = (char *) realloc((void *) buf, size * sizeof (char)); if (buftmp == NULL) { if (buf != NULL) free(buf); exit(EXIT_FAILURE); } buf = buftmp; count = snprintf(buf, size, "%04d-%02d-%02d\t%02d:%02d:00\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%d", ptr-&gt;year, ptr-&gt;month, ptr-&gt;day, ptr-&gt;hour, ptr-&gt;minute, ptr-&gt;timeframe, ptr-&gt;open, ptr-&gt;high, ptr-&gt;low, ptr-&gt;close, ptr-&gt;volume ); size += 4; } } return buf; } char * print_historico(short timeframe) { struct barlist *tmp = get_barlist(timeframe); struct bar *ptr; char * result = NULL; char * resulttmp = NULL; char * buf; int len; if (tmp) { ptr = tmp-&gt;first; while (ptr) { buf = print_bar(ptr); len = (result != NULL) ? strlen(result)+strlen(buf)+1 : strlen(buf)+1; resulttmp = (char *)realloc((void *)result, len); if (resulttmp == NULL) { if (result != NULL) free(result); exit (EXIT_FAILURE); } result = resulttmp; strncat(result, buf, strlen(buf)); free(buf); ptr = ptr-&gt;next; } } return result; } </code></pre> <p>In my main function i've got the following loop:</p> <pre><code>for (i = 1; i &lt;= 27; i++) { historico = print_historico(i); if (historico != NULL) { puts(historico); free(historico); } } </code></pre> <p>If i compile and run it fails with "realloc(): invalid next size: 0x0000000001704f60". If i run with the debugger i see it finishes the first iteration of the main loop ok, freeing the 'historico' variable. When it executes "print_historico" with i=2 it fails on the second iteration of the "while(ptr)" loop.</p> <p>I can't find a reason, any clue? I've also tried to make a small program to isolate the problem, but i wasn't able.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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