Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returned value from realloc() give a segmentation fault

#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.

like image 778
Jack Avatar asked Dec 06 '25 19:12

Jack


2 Answers

You have two fatal issues:

  1. pbuf is assigned the value of buf at init but then is never updated. realloc is not guaranted to return the same address after malloc (and the subsequent realloc calls).

  2. You are overflowing pbuf here before calling the required realloc:

    *pbuf ++= *p++, hsize ++;

like image 192
ouah Avatar answered Dec 08 '25 10:12

ouah


*pbuf ++= *p++, hsize ++;

You never initialize pBuf. Also:

tbuf = realloc(buf, BUF_SIZE);

Should be:

tbuf = realloc(buf, buf_size);

EDIT:

As @ouah noted in the comments, and considering that you do in fact initialize pBuf (though we can't see it), it seems that the way in which you manipulate p is the likely culprit. What is the type and contents of html? Is it null terminated? Are any of your *(p + n) expressions overruning it's valid bounds?

like image 41
Ed S. Avatar answered Dec 08 '25 11:12

Ed S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!