Why does result
appear to not get reallocated?
while (loc) {
char nextLine[MAX_PATH_LEN + 30];
sprintf(nextLine, "%s:%d\n", loc->item.pathname, loc->item.offset);
DPRINTF('h', ("got next line\n"));
while (spaceUsedUp + strlen(nextLine) > allocatedSize) {
allocatedSize *= 2;
}
if (realloc(result, allocatedSize) == NULL) {
perror("realloc");
}
DPRINTF('h', ("Next line length is %d\n", strlen(nextLine)));
DPRINTF('h', ("Allocated size is %d\n", allocatedSize));
DPRINTF('h', ("The size of the result is %d\n", strlen(result)));
strcat(result, nextLine); // THIS LINE CAUSES THE BUFFER OVERFLOW
spaceUsedUp += strlen(nextLine);
DPRINTF('h', ("SpaceUsedUp is %d\n", spaceUsedUp));
loc = loc->nextLocation;
}
The output is:
got next line
Next line length is 21
Allocated size is 100
The size of the result is 0
SpaceUsedUp is 21
got next line
Next line length is 21
Allocated size is 100
The size of the result is 21
SpaceUsedUp is 42
got next line
Next line length is 21
Allocated size is 100
The size of the result is 42
SpaceUsedUp is 63
got next line
Next line length is 21
Allocated size is 100
The size of the result is 63
SpaceUsedUp is 84
got next line
Next line length is 21
Allocated size is 200
The size of the result is 84
*** buffer overflow detected ***: ./proj3/disksearch terminated
You are discarding the result returned by realloc. You need to assign that value to result
. The typical usage looks like:
if ((tmp = realloc(result, allocatedSize)) == NULL) {
perror("realloc");
/* more error handling here, including (usually) freeing result or exiting */
} else {
result = tmp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With