【发布时间】:2016-03-06 14:27:53
【问题描述】:
P.S.:我几乎有所有关于“无效的下一个尺寸”的问题,但它们对我没有帮助,因为我没有另一段 malloc 或 realloc 代码,所以排除了。另外,我没有分配超出内存空间的限制,所以我在这方面也很好。
我有下面的代码给我 - *** Error in./server_issue': realloc(): invalid next size: 0x08249170 ***`.
我无法确定问题所在,我一次只分配 64 个字节,因此我没有超出内存地址空间,并且还有其他内存分配可能损坏了我的堆内存。
错误说,下一个大小无效,但正如我的最后一个日志告诉 Reallocating 64 bytes, Aborted (core dumped) 所以这意味着我仍在尝试分配 64 个字节。那么,为什么会出错呢?
对于 HTML 文件,有任何超过 256 字节的文件。
代码:(重现问题的最少代码)
#include<stdio.h>
#include<stdlib.h>
#include <stdbool.h>
#include <string.h>
typedef char BYTE;
bool load(FILE*, BYTE**, size_t*);
int main(void)
{
FILE* file = fopen("/home/university/psets/pset6/pset6_working/public/hello.html", "r");
BYTE* content;
size_t length;
load(file, &content, &length);
}
bool load(FILE* file, BYTE** content, size_t* length)
{
int totalLength = 0;
int readBytes = 0;
*content = NULL;
BYTE* fileContentTemp[64]; // working with 222222
while ((readBytes = fread(fileContentTemp, 1, 64, file)) > 0)
{
printf("Reallocating %d bytes, ", readBytes);
*content = realloc(*content, readBytes);
printf("%p\n", *content);
if(totalLength != 0)
{
memcpy(*content + totalLength + 1, fileContentTemp, readBytes);
} else{
memcpy(*content + totalLength, fileContentTemp, readBytes);
}
totalLength = totalLength + readBytes;
}
*length = totalLength;
printf("CC image: %s\n", *content);
printf("length is %d\n", *length);
printf("fileContent %p\n", *content);
return true;
}
输出:
Reallocating 64 bytes, 0x8249170
Reallocating 64 bytes, 0x8249170
*** Error in `./server_issue': realloc(): invalid next size: 0x08249170 ***
Reallocating 64 bytes, Aborted (core dumped)
更新: 即使我分配 64 个字节而不是使用
readBytes 而 realloc ,我也会得到同样的错误。由于这条线,我收到错误 - *content = realloc(*content, readBytes);
【问题讨论】:
标签: c memory memory-management realloc