2012-12-07 41 views
0

任何想法,为什么我得到错误,realloc():无效的下一个大小?realloc()无效的下一个大小

while (loc) { 
    char nextLine[MAX_PATH_LEN + 30]; 
    sprintf(nextLine, "<p>%s:%d</p>", loc->item.pathname, 
    loc->item.offset); 
    DPRINTF('h', ("Next line is: %s, length: %d\n", nextLine, strlen(nextLine))\ 
); 

    DPRINTF('h', ("spaceUsedUp is %d\n", spaceUsedUp)); 
    while (spaceUsedUp + strlen(nextLine) > allocatedSize) { 
     printf("Allocated size is now %d\n", allocatedSize); 
     allocatedSize *= 2; 
    } 

    DPRINTF('h', ("Will realloc size %d\n", allocatedSize)); 
    char *tmp = (char *)realloc(result, allocatedSize); 
    DPRINTF('h', ("Done with the realloc.\n")); 
    fflush(stdout); 
    if (tmp == NULL) { 
     perror("realloc"); 
    } 
    result = tmp; 
    tmp = NULL; 

    int theOne = (spaceUsedUp == 0) ? 0 : 1; 
    memcpy(result+spaceUsedUp-theOne, nextLine, sizeof(nextLine)); 

    spaceUsedUp += strlen(nextLine) - theOne; 
    loc = loc->nextLocation; 
    } 

输出是:

Next line is: <p>/dirA/f3:6162</p>, length: 20 
spaceUsedUp is 0 
Will realloc size 100 
Done with the realloc. 
Next line is: <p>/dirA/f3:6038</p>, length: 20 
spaceUsedUp is 19 
Will realloc size 100 
*** glibc detected *** ./proj3/disksearch: realloc(): invalid next size: 0x0000000001797fa0 *** 

回答

3

这是因为你的memcpy的sizeof(nextLine)字节,重挫已分配的内存之外。而不是sizeof(nextLine),你应该使用strlen(nextLine),事情应该没问题。

像这样的Realloc错误通常表明内存堆已损坏,这通常是由于超出边界写入或重新使用已释放指针而导致的。

Valgrind是您这些问题的朋友。

+1

'while(spaceUsedUp + strlen(nextLine)> = allocatedSize){'可能会修复它。 strcat()可以避免。 – wildplasser

相关问题