为什么
输出结果如下:
result
似乎没有被重新分配? 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;
}
输出结果如下:
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
result = malloc(...); result = NULL
。如果realloc出错,您需要跟踪result
中的旧值。(尽管通常会执行exit
或free
操作。) - William Pursell