realloc()的问题,没有被分配
问题描述:
我想读一个字符串realloc()的问题,没有被分配
char *string=malloc(sizeof(char));
char *start_string=string; //pointer to string start
while ((readch=read(file, buffer, 4000))!=0){ // read
filelen=filelen+readch; //string length
for (d=0;d<readch;d++)
*start_string++=buffer[d]; //append buffer to str
realloc(string, filelen); //realloc with new length
有时这种崩溃并出现以下错误:
malloc: *** error for object 0x1001000e0: pointer being realloc'd was not allocated
,但有时不,我不知道如何要解决这个问题。
答
realloc()
不更新传递给它的指针。如果realloc()
成功,则传入的指针为free()
d,并返回分配的内存地址。在发布的代码realloc()
中将多次尝试free(string)
,这是未定义的行为。
商店realloc()
结果:当你打电话realloc()
char* t = realloc(string, filelen);
if (t)
{
string = t;
}
答
字符串的地址可能更改。
char *string=malloc(sizeof(char));
char *start_string=string; //pointer to string start
while ((readch=read(file, buffer, 4000))!=0){ // read
filelen=filelen+readch; //string length
for (d=0;d<readch;d++)
*start_string++=buffer[d]; //append buffer to str
char* tempPtr = realloc(string, filelen); //realloc with new length
if(tempPtr) string = tempPtr;
else printf("out of memory");
}
是你们没有阅读文档... – 2013-04-24 16:33:57