When trying to reallocate memory I crash when using this code:
//value of i is currently 4096
while((c = recv(sock, htmlbff + q, MAXDATASIZE, 0)) > 0)
{
if((i - q) < MAXDATASIZE)
{
i *= 2;
if(!(tmp = realloc(htmlbff, i)))
{
free(htmlbff);
printf("\nError! Memory allocation failed!");
return 0x00;
}
htmlbff = tmp;
}
q += c;
}
it crashes because of a memory leak…. HOWEVER the following code does not crash:
while((c = recv(sock, htmlbff + q, MAXDATASIZE, 0)) > 0)
{
if((i - q) < MAXDATASIZE)
{
i *= 2;
if(!(tmp = realloc(htmlbff, i)))
{
free(htmlbff);
printf("\nError! Memory allocation failed!");
return 0x00;
}
}
htmlbff = tmp;
q += c;
}
How can moving htmlbff = tmp; outside of the if statement be fixing this problem? It doesn’t seem to set htmlbff to tmp when inside the if statement… I am extremely confused.
Let’s say you recv 4096 bytes twice in a row. What happens is:
htmlbff + 0.qis still 0,i - q== 4096, so no allocation is done.qis bumped up by 4096.htmlbff + 4096. But wait, since we didn’t resize it last iteration,htmlbffis only 4096 bytes big, and the entire read spills out of the buffer!Try this instead…