#define BUF_SIZE 10
char *html = "foo:baa\r\nxxx:yyyy:\r\nLocation:........................................\r\Connection:close\r\n\r\n";
char *p = (char*)html, *buf, *pbuf, *tbuf;
int buf_size = BUF_SIZE, hsize = 0;
if((buf = malloc(buf_size)) == NULL) FAILED("NO MEMORY!\n");
pbuf = buf;
while(*p != '\0' && *(p + 1) != '\r' && *(p + 2) != '\n') {
if((hsize + 1) >= buf_size) {
printf("Do realloc!\n");
buf_size += BUF_SIZE + 2;
tbuf = realloc(buf, buf_size); // BUF_SIZE
if(tbuf != NULL) {
buf = tbuf;
} else {
printf(" NO MEMORY!\n");
exit(1);
}
}
*pbuf ++= *p++, hsize ++;
}
But it give an
Do realloc!
Do realloc!
Stack trace:
Frame Function Args
0022A814 7798EFA3 (000000FC, 0000EA60, 00000000, 0022A948)
0022A828 7798EF52 (000000FC, 0000EA60, 000000A4, 0022A924)
0022A948 610DB059 (00000000, 00000001, 0022A978, 0000000C)
0022AA38 610D841E (00000000, 61102908, 003B0023, 00230000)
0022AA98 610D88EE (20038878, 0000000C, 0022AAC8, 00000006)
0022AB48 610D8A40 (00000E3C, 00000006, 00000001, 20010340)
0022AB68 610D8A6C (00000006, 0022CE80, 0022ABD4, 20038883)
0022AB98 610D8CF5 (004031AA, 20010340, 0022ABE8, 61138596)
20010348 6110F935 (73756A2E, DF0DF02E, 200000C8, 00000000)
I have no idea how to fix this! Actually, I am not sure that it’s a really segmentation fault.
You have two fatal issues:
pbufis assigned the value ofbufat init but then is never updated.reallocis not guaranted to return the same address aftermalloc(and the subsequentrealloccalls).You are overflowing
pbufhere before calling the requiredrealloc:*pbuf ++= *p++, hsize ++;