我有以下代码:
FILE *fp;
fp = fopen("input_file","r");
size_t newsize = 1;
char buffer[MAX_SIZE];
char *text;
text = malloc(sizeof(char) * newsize);
strcpy(text,"");
while (fgets(buffer,sizeof(buffer),fp) != NULL)
{
newsize += strlen(buffer)
text = realloc(text,newsize);
strcat(text,buffer);
}
在我程序的末尾,我 free(text)
。每个Realloc之后我都需要释放吗?现在我的程序"工作",但是当我通过Valgrind运行它时,我会遇到很多错误。
编辑:我编辑了所有其他代码,这是我甚至在Realloc Part
之前遇到的错误==3953== Warning: client switching stacks? SP change: 0x7ff0004c0 --> 0x7fe85f190
==3953== to suppress, use: --max-stackframe=8000304 or greater
==3953== Invalid write of size 4
==3953== at 0x40076E: main (p21.c:37)
==3953== Address 0x7fe85f19c is on thread 1's stack
==3953==
==3953== Invalid write of size 8
==3953== at 0x400774: main (p21.c:37)
==3953== Address 0x7fe85f190 is on thread 1's stack
==3953==
==3953== Invalid write of size 8
==3953== at 0x400793: main (p21.c:43)
==3953== Address 0x7fe85f188 is on thread 1's stack
==3953==
==3953== Invalid read of size 8
==3953== at 0x4E8C38D: __fopen_maybe_mmap (iofopen.c:60)
==3953== by 0x400797: main (p21.c:43)
==3953== Address 0x7fe85f188 is on thread 1's stack
==3953==
==3953== Warning: client switching stacks? SP change: 0x7fe85f190 --> 0x7ff0004c0
==3953== to suppress, use: --max-stackframe=8000304 or greater
我需要在每个realloc之后释放吗?
否。realloc
释放旧内存块,并为您提供一个新的内存块。
除非它可以扩展内存块而无需释放内存块,在这种情况下,它可以做到这一点并将相同的块返回。但在这种情况下,由于没有任何额外的分配,因此没有什么可释放的。